Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Lambda: Comparator

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)       -> {}) 
like image 288
Nunyet de Can Calçada Avatar asked May 28 '17 09:05

Nunyet de Can Calçada


People also ask

Can we use lambda with comparable?

The answer to that question is Yes, you can use a lambda expression to implement Comparator and Comparable interface in Java, and not just these two interfaces but to implement any interface, which has only one abstract method because those are known as SAM (Single Abstract Method) Type and lambda expression in Java ...


2 Answers

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

It would be nicer written like this:

.sort(Comparator.comparingLong(Message::getTime)) 
like image 101
Eugene Avatar answered Oct 06 '22 00:10

Eugene


Lambda

The lambda can be seen as the shorthand of somewhat cumbersome anonymous class:

Java8 version:

Collections.sort(list, (o1, o2) -> o1.getTime() - o2.getTime()); 

Pre-Java8 version:

    Collections.sort(list, new Comparator<Message>() {         @Override         public int compare(Message o1, Message o2) {             return o1.getTime() - o2.getTime();         }     });  

So, every time you are confused how to write a right lambda, you may try to write a pre-lambda version, and see how it is wrong.

Application

In your specific problem, you can see the compare returns int, where your getTime returns long, which is the source of error.

You may use either method as other answer method, like:

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

Notice

  • You should avoid using - in Comparator, which may causes overflow, in some cases, and crash your program.
like image 25
Tony Avatar answered Oct 06 '22 01:10

Tony