I want to sort a list with Lambda:
List messagesByDeviceType = new ArrayList();
messagesByDeviceType.sort((Message o1, Messag
You should change
messagesByDeviceType.sort( (Message o1, Message o2) -> o1.getTime() - o2.getTime() );
to
messagesByDeviceType.sort(
Comparator.comparing((Message m) -> m.getTime())
);
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:
messagesByDeviceType.sort(
Comparator
.comparing((Message m) -> m.getTime())
.thenComparing((m) -> m.getSender())
);
To reverse the order of any Comparator
, chain the reveresed()
method to it, e.g. to sort first by time descending, and then by sender:
messagesByDeviceType.sort(
Comparator
.comparing((Message m) -> m.getTime())
.reversed()
.thenComparing((m) -> m.getSender())
);
See also https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html