【发布时间】:2019-04-18 05:53:12
【问题描述】:
我想按可空字段之一对对象列表进行排序。
为了避免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
}
}
我怎样才能对这种列表进行排序?
【问题讨论】:
-
@rellocswood 请发布您的解决方案作为答案,而不是编辑问题。
标签: java collections java-8 java-stream comparator