Home > Java > javaTutorial > body text

Why Does Collectors.toMap Throw a NullPointerException for Null Values?

Mary-Kate Olsen
Release: 2024-11-11 13:44:03
Original
212 people have browsed it

Why Does Collectors.toMap Throw a NullPointerException for Null Values?

Null Values in Collectors.toMap: An Explanation and Java 8 Solutions

Java 8's Collectors.toMap method throws a NullPointerException when it encounters null values as its second argument, despite maps allowing for null values as values. This peculiar behavior has sparked confusion among developers.

Reason Behind the Behavior

The underlying reason for this behavior is a known bug in the OpenJDK implementation of Collectors.toMap. The method attempts to merge the current and new values for a given key using the HashMap.merge operation. However, this operation doesn't handle null values gracefully, resulting in the exception.

Java 8 Solution

To work around this issue, you can use the following approach:

Map collect = list.stream().collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getAnswer()), HashMap::putAll);

This code creates a new HashMap and uses a custom collector to populate it by invoking the put method directly. This approach allows null values to be added.

Other Considerations

Unlike Collectors.toMap, the provided solution will silently replace values if the same key appears multiple times. If this is not desired, you may want to consider alternative solutions provided in the comments section.

By understanding the reason behind the NullPointerException and using the workaround, you can effectively handle null values when using Collectors.toMap.

The above is the detailed content of Why Does Collectors.toMap Throw a NullPointerException for Null Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template