Java 8 Lambda:比较器 [英] Java 8 Lambda: Comparator
本文介绍了Java 8 Lambda:比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用Lambda对列表进行排序:
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)
-> {})
推荐答案
比较器#compareTo
返回 int
;而 getTime
显然是 long
。
这将是更好的写得像这样:
It would be nicer written like this:
.sort(Comparator.comparingLong(Message::getTime))
这篇关于Java 8 Lambda:比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文