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)
-> {})
You should change
to
That assumes that the value is
Comparable
, which provides a natural sort order.If you want to add more fields then you can can chain them to the Comparator. e.g. to sort first by time, and then by sender:
To reverse the order of any
Comparator
, chain thereveresed()
method to it, e.g. to sort first by time descending, and then by sender:See also https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
Comparator#compareTo
returns anint
; whilegetTime
is obviouslylong
.It would be nicer written like this:
The compare() method must return an int, and it seems yours is returning a long.
You can change it this into:
Long.compare(o1.getTime(),o2.getTime())
Well explained regarding lambda comparator in the below presented video link.
https://youtu.be/r7mYbTmWtUg
Comparator
We use comparator interface to sort homogeneous and heterogeneous elements for default, customized sorting order.
Anonymous Classes how to sort a list of objects in prior versions of Java 8 using inner Classes.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
Java 8
Lambda Expressions
uing compare methodBasic Sort with Lambda Support
Using Extracted Key and Comparing method: A comparator that compares by an extracted key. Pass references using :: keyword.
Sample Test Code:
See these posts also:
The
Comparator
'scompare()
method must return anint
, and it seems yours is returning along
.You can change it to:
This is assuming (based on your error message) that
o1.getTime()
returns along
.Lambda
The lambda can be seen as the shorthand of somewhat cumbersome anonymous class:
Java8 version:
Pre-Java8 version:
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
returnsint
, where yourgetTime
returns long, which is the source of error.You may use either method as other answer method, like:
Notice
-
inComparator
, which may causes overflow, in some cases, and crash your program.