i've got a list form DB, then i use the function above to translate it to a hashMap(already check out this list is not null or emptiy). but the sonarLint keeps telling me that the function above might return null, and it might caught NPE. And when i use enhanced for loop, the warning will disappear.
i can't find out why eventualy, hope you help me out of here. Thanks a lot.
the code below that sonarLint says might return null:
return objectList.stream().filter(Objects::nonNull).collect(Collectors.toMap(Object::getField, Function.identity()));
the code below that sonarLint says it's ok:
Map<String, Object> map = new HashMap<>(); for(Object obj : ObjectList) { map.put(obj.getField(), obj); } return map;
No, it won't. The whole collection framework is build in ways to ensure that you don't end up with null where some empty collection could be provided instead.
So: the collector will not return null.
But: depending on your context, obj.getField()
might return null. And there are conditions where collection methods throw NPEs for null keys.