// 填充数据
List<Long> testList = Lists.newArrayList(1L, null, 2L, 3L);
// 过滤数据,如果不加null 校验会报空指针异常 。因为null != 1 表达式在java中不成立所以必须先校验是否为null,当然如果筛选的源数据没有空值那可以不用校验
// 筛选出null值和非1数据
List<Long> filterList = testList.stream().filter(temp -> temp == null || temp != 1).collect(Collectors.toList());
// 筛选出非null且非1数据
List<Long> filterList = testList.stream().filter(temp -> temp != null && temp != 1).collect(Collectors.toList());
java8 stream().filter() 未加null校验导致空指针问题
最新推荐文章于 2024-09-26 10:13:16 发布
本文介绍了如何使用Java集合框架中的Stream API进行数据过滤操作,特别是针对包含null值的情况。通过示例展示了如何筛选出null值和非特定值(如1)的数据,以及如何过滤出非null且非特定值的数据,强调了在处理可能含有null值的集合时进行校验的重要性。
1711

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



