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) -> {})
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 ...
Comparator#compareTo
returns an int
; while getTime
is obviously long
.
It would be nicer written like this:
.sort(Comparator.comparingLong(Message::getTime))
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.
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())
-
in Comparator
, which may causes overflow, in some cases, and crash your program.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With