Java NullPointerException: element cannot be mapped to a null key问题解决

野性酷女 2023-09-30 09:26 138阅读 0赞

问题描述:

java.lang.NullPointerException: element cannot be mapped to a null key

问题分析:

1、使用Collectors.groupingBy()进行分组时,分组值存在null值。

  1. List<String> strList = new ArrayList<>(Arrays.asList("11", "12", "13", null, null));
  2. Map<String, List<String>> map = strList.stream().collect(Collectors.groupingBy(x -> x));

解决办法:分组值为null时,默认值为空字符。

  1. List<String> strList = new ArrayList<>(Arrays.asList("11", "12", "13", null, null));
  2. Map<String, List<String>> map = strList.stream().collect(Collectors.groupingBy(x -> StrUtil.isEmpty(x) ? "" : x));

发表评论

表情:
评论列表 (有 0 条评论,138人围观)

还没有评论,来说两句吧...

相关阅读