4

Hi I have this (what i assume to be) really trivial code:

List<Integer> f = new LinkedList<Integer>();
    Collections.sort(f, (Integer f1, Integer f2) -> {
        Integer.compare(f1,f2);
    });

However, I get the following compile-error:

Cannot convert from Comparator<Integer> to Comparator<? super T>

This isn't very helpful - what is going wrong?

5
  • 4
    This is the place for the almost mandatory reference to “When to use LinkedList over ArrayList?” as everyone using LinkedList most likely haven’t read it… Commented Jan 23, 2017 at 14:26
  • I don't always use Lists, but when I do I use Vector Commented Jan 23, 2017 at 14:43
  • You should always use Lists, where appropriate. But prefer ArrayList. There is almost never a reason for LinkedList nor Vector. Commented Jan 23, 2017 at 14:58
  • 1
    @bharal if you prefer/use Vectors, then you need to read this (I did too and learned !) : stackoverflow.com/questions/1386275/… Commented Jan 23, 2017 at 15:00
  • @Holger everyone here is very serious, no? Commented Jan 24, 2017 at 14:53

1 Answer 1

12

You can use method reference in this case:

 List<Integer> f = new LinkedList<>();
 Collections.sort(f, Integer::compare);

In the original code there is missing return statement:

 Collections.sort(f, (f1 ,  f2) -> {
        return Integer.compare(f1,f2);
 });

return must be used if lambda contains {}

Same thing without return and brackets:

Collections.sort(f, (f1 ,  f2) -> 
         Integer.compare(f1,f2)
);

A few useful notes from comments section below:

It is possible to just use Collections.sort(f) and rely on natural ordering. by Jean-François Savard

Since Java 8 List interface has sort method which can also be used f.sort(null); f.sort(Comparator.naturalOrder()); or, Collections.sort(f, Comparator.naturalOrder()); by Holger

Sign up to request clarification or add additional context in comments.

6 Comments

Um, but what if i just wanted to do it how i did it - is that impossible? What am i doing wrong? Thanks for the answer, but it doesn't answer my question!
thanks so much, i didn't realise i'd messed up the return {} stuff, good to know.
@bharal I updated my original answer, but the shortest way is to use method reference.
You could simply do Collections.sort(f) and rely on natural ordering.
Or f.sort(null);. Alternatively, f.sort(Comparator.naturalOrder()); or, Collections.sort(f, Comparator.naturalOrder()); will do as well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.