Video in progress
Why does Collectors.toMap() throw an NPE on a null value, when HashMap accepts null?
toMap is built on HashMap.merge() semantics: the variant with a merge function calls merge directly, while the two-argument variant (Java 9+) checks the value with Objects.requireNonNull. By contract merge rejects a null value, so you get an NPE when the value, not the key, is null.
📖 Answer
A frequent case in prod:
Map<Long, String> phones = users.stream()
.collect(Collectors.toMap(User::id, User::phone));
// one user with no phone: NullPointerException
The stack trace leads to HashMap.merge in Java 8, and in Java 9+ to Objects.requireNonNull and Collectors.uniqKeysMapAccumulator for the two-argument toMap, so the cause isn't obvious at first glance. For merge, null has a special meaning of "remove the value", so toMap also doesn't allow putting a null value.
Solutions, depending on the situation:
// 1) drop the ones with a null value
users.stream()
.filter(u -> u.phone() != null)
.collect(Collectors.toMap(User::id, User::phone));
// 2) replace null with an Optional or a default value
Collectors.toMap(User::id, u -> Objects.requireNonNullElse(u.phone(), ""));
// 3) if you really need a null value, collect into a HashMap yourself
Map<Long, String> m = users.stream().collect(
HashMap::new, (map, u) -> map.put(u.id(), u.phone()), HashMap::putAll);
The third variant has no duplicate key check: the last one wins. Choose it knowingly.
With groupingBy it's the reverse: values may be null, and if the key is null you get an NPE.
General advice: storing a null value in a map often confuses "no key" with "no value". If you can, don't store it at all.
Sign up to mark studied questions and save your progress.