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>
toComparator<? super T>
This isn't very helpful - what is going wrong?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With