Home > Java > javaTutorial > body text

Why Does Collectors.toMap Throw a NullPointerException When Values Are Null?

Susan Sarandon
Release: 2024-11-10 15:32:03
Original
477 people have browsed it

Why Does Collectors.toMap Throw a NullPointerException When Values Are Null?

NullPointerException in Collectors.toMap with Null Entry Values

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);
Copy after login

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!

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