Home  >  Article  >  Java  >  Why does Collectors.toMap() throw a NullPointerException with null entry values?

Why does Collectors.toMap() throw a NullPointerException with null entry values?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-11 11:46:03599browse

Why does Collectors.toMap() throw a NullPointerException with null entry values?

NullPointerException in Collectors.toMap() with Null Entry Values

When attempting to utilize Collectors.toMap() to transform a stream of objects into a map, a NullPointerException can arise if one or more of the values within the stream are null. This behavior may seem counterintuitive, considering that maps are capable of holding null values.

This exception occurs due to a known bug in OpenJDK. To mitigate this issue, a workaround is available:

Although not elegant, this approach effectively resolves the issue. The resulting map will contain the key-value pairs from the stream, including any null values.

Note that this workaround has a limitation: if the stream contains duplicate keys with different values, the map will silently replace the existing value with the new one. To address this, refer to the link provided in the comment section.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn