Java - Lambda 之 stream().collect(Collectors.toList()) 空指针 NPE

慕犹清

关注

阅读 66

2022-05-18


问题

举例这段代码,在 collect 之前不仅 SupplierHistoryPO 不能为 null,而且 getOrder 也不允许为 null,否则报错NPE

List<SupplierRowDTO> rows = histories.stream()
.filter(h -> h.getAmount() > 0)
.sorted(Comparator.comparingInt(SupplierHistoryPO::getOrder))
.collect(Collectors.toList());


解决

可以在 filter 里对 SupplierHistoryPO & SupplierHistoryPO::getOrder 都需要判空过滤,否则很危险!


精彩评论(0)

0 0 举报