java 8,按属性排序对象列表,不带自定义比较器 [英] java 8, Sort list of objects by attribute without custom comparator
本文介绍了java 8,按属性排序对象列表,不带自定义比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
完成这项工作的最简洁方法是什么?
What is the cleanest short way to get this done ?
class AnObject{
Long attr;
}
List<AnObject> list;
我知道可以使用AnObject的自定义比较器来完成。对于这种情况,是不是已经开箱即用?种类
I know it can be done with custom comparator for AnObject. Isn't there something ready out of the box for such case ? kind of
Collections.sort(list, X.attr ) ;
推荐答案
假设你确实有列表< AnObject>
,您只需要
Assuming you actually have a List<AnObject>
, all you need is
list.sort(Comparator.comparing(a -> a.attr));
如果通过不使用公共字段而不是使用访问器方法来使代码清洁,则它变得更加清晰:
If you make you code clean by not using public fields, but accessor methods, it becomes even cleaner:
list.sort(Comparator.comparing(AnObject::getAttr));
这篇关于java 8,按属性排序对象列表,不带自定义比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文