Collectors.toMap throws a NullPointerException when one of the values is null. This behavior is surprising because maps can contain null values without any problems. Why is this restriction in place for Collectors.toMap?
The reason for this restriction is that Collectors.toMap uses a HashMap internally. HashMaps do not allow null values for keys, but they allow null values for values. However, Collectors.toMap assumes that all values are non-null, and it throws a NullPointerException if this assumption is violated.
Java 8 does not provide a nice way to fix this problem. You can either revert to a plain old for loop or use a workaround like the one below:
Map<Integer, Boolean> collect = list.stream() .collect(HashMap::new, (m,v)->m.put(v.getId(), v.getAnswer()), HashMap::putAll);
This workaround uses a HashMap constructor that takes a supplier as an argument. The supplier is used to create a new map instance if the stream is empty. In this case, the supplier creates a new HashMap with a default capacity of 16 and a load factor of 0.75.
The workaround then uses the putAll method to add all of the elements from the stream to the map. The putAll method merges the elements from the stream into the map, replacing any existing elements with the same key.
This workaround is not as clean as the Collectors.toMap method, but it works. It also preserves the order of the elements in the stream, which Collectors.toMap does not do.
The above is the detailed content of Why Does Collectors.toMap Throw a NullPointerException When Values Are Null?. For more information, please follow other related articles on the PHP Chinese website!