我想按可为空的字段之一对对象列表进行排序。
为了避免NullPointerexception
,我使用Comparator.nullsLast
。但是还是出现了异常:
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
}
}
如何对这种列表进行排序?
最佳答案
你应该使用 Comparator.nullsLast
两次:
list.sort(nullsLast(comparing(Bean::getVal, nullsLast(naturalOrder()))));
- 第一个
nullsLast
将处理Bean
对象为空的情况。 - 第二个
nullsLast
将处理Bean::getVal
的返回值为 null 的情况。
如果您确定列表中没有任何 null
值,那么您可以省略第一个 nullsLast
(如@Holger 所述):
list.sort(comparing(Bean::getVal, nullsLast(naturalOrder())));
关于java - Comparator.nullsLast 不会避免 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53314193/