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?
有点像这样:
Collections.sort(list, X.attr);
推荐答案
假设你真的有一个List
,你只需要
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屋!
查看全文