一尘不染

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

阅读 190

收藏
2020-12-03

共1个答案

一尘不染

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

这样写会更好:

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