小编典典

Java 8 Lambda:比较器

java

我想用Lambda排序列表:

List<Message> messagesByDeviceType = new ArrayList<Message>();      
messagesByDeviceType.sort((Message o1, Message o2)->o1.getTime()-o2.getTime());

但是我得到了这个编译错误:

 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) 
     -> {})

阅读 218

收藏
2020-12-03

共1个答案

小编典典

Comparator#compareTo返回一个int; 而getTime显然是long

这样写会更好:

 .sort(Comparator.comparingLong(Message::getTime))
2020-12-03