NullPointerException Encountered in Collectors.toMap with Null Entry Values
Introduction
In Java 8, Collectors.toMap is a convenient method for creating a Map from a stream of key-value pairs. However, this method throws a NullPointerException if one of the values in the stream is null. This seems odd, given that Maps can contain null values without any issues.
Reason for Null Exception
The reason behind this behavior is that the default implementation of Collectors.toMap uses a HashMap as the underlying data structure. HashMaps do not allow null values for keys, but they do allow null values for values. However, when Collectors.toMap encounters a null value for a key, it attempts to use the default value for the value (which is null), and this results in the NullPointerException.
Java 8 Solution
To fix this issue in Java 8, we can use a workaround that involves manually creating a HashMap and populating it with the key-value pairs from the stream:
Map<Integer, Boolean> collect = list.stream() .collect(HashMap::new, (m,v)->m.put(v.getId(), v.getAnswer()), HashMap::putAll);
This workaround is not particularly elegant, but it will produce the expected result: a Map containing the key-value pairs from the stream, with null values for any keys that had null values in the stream.
Considerations
It is important to note that this workaround has the following considerations:
If these considerations are unacceptable for your use case, you may need to consider alternative approaches, such as using a different Collector implementation or reverting to a plain old for loop.
The above is the detailed content of Why Does Collectors.toMap Throw a NullPointerException with Null Entry Values?. For more information, please follow other related articles on the PHP Chinese website!