Java 8 Lambda: Comparator

Nunyet de Can Calçada picture Nunyet de Can Calçada · May 28, 2017 · Viewed 39.1k times · Source

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) 
     -> {})

Answer

Eugene picture Eugene · May 28, 2017

Comparator#compareTo returns an int; while getTime is obviously long.

It would be nicer written like this:

 .sort(Comparator.comparingLong(Message::getTime))