Java 8 Lambda not working?

Hi, I have (what I assume) a 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 compilation error:

Unable to convert from Comparator<Integer>toComparator<? super T>

This is not very useful - what is wrong?

+4
source share
1 answer

In this case, you can use the link to the method:

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

There is no return statement in the source code:

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

return should be used if lambda contains{}

The same without return and brackets:

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

Some useful notes from the comments section below:

You can use Collections.sort(f)and rely on the natural order. Jean-Francois Savard

Java 8 List sort, f.sort(null); f.sort(Comparator.naturalOrder()); , Collections.sort(f, Comparator.naturalOrder()); Holger

+12

Source: https://habr.com/ru/post/1667544/


All Articles