I want to sort a list with Lambda:
List messagesByDeviceType = new ArrayList();
messagesByDeviceType.sort((Message o1, Messag
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() {
@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.