在使用stream流的Collectors.groupingBy做分组统计时(示例代码如下)

Map<String, Long> collect = list.stream().collect(Collectors.groupingBy(User::getUserName, Collectors.counting()));

如果统计的字段userName有null值则会报如下错误

java.lang.NullPointerException: element cannot be mapped to a null keyat java.util.Objects.requireNonNull(Objects.java:228)at java.util.stream.Collectors.lambda$groupingBy$45(Collectors.java:907)


解决方法为在统计之前增加一个filter方法将null值事先过滤掉。代码如下:

Map<String, Long> collect = list.stream().filter((item) -> StringUtils.isNotBlank(item.getUserName())).collect(Collectors.groupingBy(User::getUserName, Collectors.counting()));