类A的集合aList,需要按A的字段id进行排序
使用lambda表达式进行过滤、排序时,出现了空指针异常
改之前代码:
List<A> aList1 = aList.stream().distinct().sorted(
Comparator.comparing(A::getId()).reversed()
).collect(Collectors.toList());
发现是排序的字段为空导致,需要添加处理null的操作
改之后代码:
List<A> aList1 = aList.stream().distinct().sorted(
Comparator.comparing(A::getId, Comparator.nullsFirst(Long::compareTo)).reversed()
).collect(Collectors.toList());
本文介绍在使用Java Stream API处理类A集合时,如何解决因字段id为空而导致的空指针异常问题。通过对比改前后的代码示例,展示了如何在排序过程中正确处理null值,确保程序的稳定运行。
1583

被折叠的 条评论
为什么被折叠?



