Java 8 Lambda: Comparator

Viewed 64230

I want to sort a list with Lambda:

List<Message> messagesByDeviceType = new ArrayList<Message>();      
messagesByDeviceType.sort((Message o1, Message o2)->o1.getTime()-o2.getTime());

But I got this compilation error:

 Multiple markers at this line
    - Type mismatch: cannot convert from long to int
    - The method sort(Comparator<? super Message>) in the type List<Message> is not applicable for the arguments ((Message o1, Message o2) 
     -> {})
7 Answers

The compare() method must return an int, and it seems yours is returning a long.

You can change it this into:

Long.compare(o1.getTime(),o2.getTime())

Well explained regarding lambda comparator in the below presented video link.

lamda comparator

In the place of Developer write your class name 

    Comparator<Developer> byName = 
        (Developer o1, Developer o2)->o1.getName().compareTo(o2.getName());
Related