list java 8,在没有自定义比较器的情况下按属性对对象列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33487063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:09:45  来源:igfitidea点击:

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

listsortinglambdajava-8

提问by Nabil Sham

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

我知道可以使用 AnObject 的自定义比较器来完成。对于这种情况,没有现成的东西吗?的种类

 Collections.sort(list, X.attr ) ;

回答by JB Nizet

Assuming you actually have a List<AnObject>, all you need is

假设你真的有一个List<AnObject>,你所需要的就是

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

回答by Alex

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

作为@JB Nizet 答案的补充,如果您的属性可以为空,

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

may throw a NPE.

可能会抛出 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.

这将首先或最后放置空值。

回答by Warren Crasta

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

上面 JB Nizet 和 Alex 的回答的空安全选项是执行以下操作:

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

or

或者

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