objectList.stream().collect(Collectors.toMap(Object::getField, Function.identity)) return 会为空吗?

will objectList.stream().collect(Collectors.toMap(Object::getField, Function.identity)) return null?

我有一个列表形式的数据库,然后我使用上面的函数将它转换为一个 hashMap(已经检查过这个列表不是 null 或 emptiy)。但是 sonarLint 一直告诉我上面的函数可能 return null,并且它可能会捕获 NPE。当我使用增强的 for 循环时,警告将消失。

我最终找不到原因,希望你能帮助我离开这里。 非常感谢。

sonarLint 说的下面的代码可能 return null:

return objectList.stream().filter(Objects::nonNull).collect(Collectors.toMap(Object::getField, Function.identity()));

sonarLint 下面的代码说没问题:

   Map<String, Object> map = new HashMap<>();
   for(Object obj : ObjectList) {
       map.put(obj.getField(), obj);
   }
   return map;

不,不会。整个集合框架的构建方式可确保您不会以 null 结束,而可以提供一些空集合。

因此:collector 不会 return null。

但是:根据您的上下文,obj.getField() 可能 return 为空。在某些情况下,收集方法会为 null keys.

抛出 NPE

你的代码很好处理not null,可能值得去看看sonar规则,也可以参考一下Check condition inside lambda expression using Stream API has SonarQube issues