Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda Not working?

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?

like image 711
bharal Avatar asked Dec 14 '22 01:12

bharal


1 Answers

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

like image 189
Anton Balaniuc Avatar answered Feb 06 '23 00:02

Anton Balaniuc