Comparator.nullsLast不能避免NullPointerException [英] Comparator.nullsLast does not avoid NullPointerException
本文介绍了Comparator.nullsLast不能避免NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按可为空的字段之一对对象列表进行排序.
I want to sort a list of objects by one of nullable fields.
为了避免 NullPointerexception
,我使用了 Comparator.nullsLast
.但是仍然会发生例外情况:
In order to avoid NullPointerexception
I use Comparator.nullsLast
. But the exception still occurs:
public class Test {
public static void main(String[] args) {
List<Bean> l = new ArrayList<>();
for (int i=0;i<5;i++) {
Bean b = new Bean("name_"+i,i);
l.add(b);
}
l.get(2).setVal(null);
System.out.println(l);
Collections.sort(l, Comparator.nullsLast(Comparator.comparing(Bean::getVal)));
System.out.println(l);
}
static class Bean{
String name;
Integer val;
// omit getters & setters & constructor
}
}
如何对这种列表进行排序?
How can I sort this kind of list?
推荐答案
您应该两次使用 Comparator.nullsLast
:
list.sort(nullsLast(comparing(Bean::getVal, nullsLast(naturalOrder()))));
- 第一个
nullsLast
将处理Bean
对象为null的情况. - 第二个
nullsLast
将处理Bean :: getVal
的返回值为null的情况. - First
nullsLast
will handle the cases when theBean
objects are null. - Second
nullsLast
will handle the cases when the return value ofBean::getVal
is null.
如果您确定列表中没有任何 null
值,则可以省略第一个 nullsLast
(如@Holger所指出):>
In case you're sure there aren't any null
values in your list then you can omit the first nullsLast
(as noted by @Holger) :
list.sort(comparing(Bean::getVal, nullsLast(naturalOrder())));
这篇关于Comparator.nullsLast不能避免NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文