java 8, Sort list of objects by attribute without custom comparator

别说谁变了你拦得住时间么 提交于 2019-12-28 03:47:09

问题


What is the cleanest short way to get this done ?

 class AnObject{
     Long  attr;
 }

 List<AnObject> list; 

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 ) ;

回答1:


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));



回答2:


As a complement to @JB Nizet's answer, if your attr is nullable,

list.sort(Comparator.comparing(AnObject::getAttr));

may throw a NPE.

If you also want to sort null values, you can consider

    list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsFirst(Comparator.naturalOrder())));

or

    list.sort(Comparator.comparing(a -> a.attr, Comparator.nullsLast(Comparator.naturalOrder())));

which will put nulls first or last.




回答3:


A null-safe option to JB Nizet's and Alex's answer above would be to do the following:

list.sort(Comparator.comparing(AnObject::getAttr, Comparator.nullsFirst(Comparator.naturalOrder())));

or

list.sort(Comparator.comparing(AnObject::getAttr, Comparator.nullsLast(Comparator.naturalOrder())));


来源:https://stackoverflow.com/questions/33487063/java-8-sort-list-of-objects-by-attribute-without-custom-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!