Comparator.nullsLast不会避免NullPointerException。
- 论坛
- Comparator.nullsLast不会避免NullPointerException。
19 浏览
Comparator.nullsLast不会避免NullPointerException。
我想按照可为空字段之一对对象列表进行排序。
为了避免NullPointerexception
,我使用Comparator.nullsLast
。但是异常仍然发生:
public class Test { public static void main(String[] args) { Listl = 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 } }
我该如何对这种类型的列表进行排序?