Java 8 Lambda: Comparator
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
-
inComparator
, which may causes overflow, in some cases, and crash your program.
Comparator#compareTo
returns an int
; while getTime
is obviously long
.
It would be nicer written like this:
.sort(Comparator.comparingLong(Message::getTime))