NullPointerException in Collectors.toMap with null values
Codemia Knowledge Hub ·
Collectors.toMap throws a NullPointerException when the value-mapping function returns null, even though HashMap.put accepts null values. The cause is that toMap rejects null values on purpose: Java 8 goes through Map.merge, and Java 9+ adds an explicit Objects.requireNonNull check on each value. Depending on what you need, filter nulls out, substitute a default, or use a manual collector that permits nulls.
Why toMap rejects null values
The two-argument form of Collectors.toMap looks straightforward:
But if any person's email is null, this throws:
That trace is from Java 17, where the two-argument toMap checks each value with Objects.requireNonNull. On Java 8 the same call fails inside HashMap.merge, and the three-argument form still uses Map.merge today. The merge contract requires non-null values because it must distinguish "this key maps to null" from "this key is absent" when applying the merge function.
A minimal reproduction:
Solution 1: filter out null values
When entries with null values should simply be left out, filtering is the cleanest approach:
Result: {[email protected], [email protected]}
Bob is excluded entirely. This fits when downstream code treats a missing key the same as a null value, which is true of most map lookups.
When both keys and values might be null, filter on both:
Solution 2: substitute a default value
When the map must contain every key, replace nulls with a sentinel before collecting:
Result: {[email protected], Bob=, [email protected]}
Choose the default carefully. An empty string, a domain-specific placeholder like "not_provided", or Optional.empty() (if you switch to Map<String, Optional<String>>) each tell downstream consumers something different.
Objects.requireNonNullElse (Java 9+) is a shorter alternative to the ternary.
Solution 3: a manual collector that stores nulls
When the map genuinely needs actual null values (not a sentinel), Collectors.toMap is the wrong tool. Use the three-argument collect method with explicit accumulation:
Result: {[email protected], Bob=null, [email protected]}
This works because HashMap.put accepts null values. The three arguments are:
- Supplier: creates the result container (
HashMap::new). - Accumulator: adds each element to the container.
- Combiner: merges two containers during parallel execution.
Extracting a reusable utility
If the pattern shows up often, extract it:
Duplicate keys are a separate failure
Even with nulls handled, toMap throws IllegalStateException if two elements produce the same key:
The three-argument form of toMap takes a merge function to resolve conflicts:
Common merge strategies:
Null handling and duplicate-key handling are independent. You may need both in one pipeline, but they need different fixes.
When to switch from toMap to groupingBy
If several elements can share a key and you want to keep all values, Collectors.groupingBy often fits better than toMap with a merge function:
groupingBy never throws on duplicate keys because it expects multiple values per key. The grouped lists can also contain null values without issues.
Comparison of approaches
| Approach | Null values in result? | Duplicate key handling | Readability |
filter + toMap | No (excluded) | Throws by default | High |
Default substitution + toMap | No (replaced) | Throws by default | High |
Manual collect with HashMap | Yes | Last writer wins | Medium |
Custom toNullableMap utility | Yes | Configurable | High (after initial definition) |
groupingBy | Yes (in lists) | Built-in (groups) | High |
Mistakes to avoid
Assuming Collectors.toMap behaves like HashMap.put. This is the most common surprise. toMap rejects null values (through Map.merge or an explicit null check); HashMap.put does not.
Fixing nulls but forgetting duplicate keys. Filtering nulls does not prevent IllegalStateException from duplicates, and a merge function does not prevent NullPointerException from null values.
Using a sentinel that looks like real data. A default of "[email protected]" is dangerous if downstream code might send email to it. Use clearly synthetic values like empty strings or dedicated constants.
Ignoring parallel streams with the manual collector. The HashMap::putAll combiner means last writer wins. If two parallel partitions contain the same key, one value is silently lost. If that is unacceptable, add conflict detection in the combiner.
Expecting toUnmodifiableMap (Java 10+) to help. It also uses merge internally and also throws on null values.
Over-engineering with Optional. Wrapping every value in Optional<String> gives a Map<K, Optional<V>> that is verbose to consume. Prefer filtering or defaults unless you specifically need to distinguish "present but empty" from "absent."
Related reading
- NullPointerException in Java with no StackTrace
- NullPointerException in Junit 5 MockBean
- Number of days between two dates in Joda-Time
- Number of lines in a file in Java
- NullPointerException when trying to access views in a Kotlin fragment
- Numpy is installed but still getting error
- object kafka is not a member of package org.apache
- Object not serializable (org.apache.kafka.clients.consumer.ConsumerRecord) in Java spark kafka streaming
System design interview problems on this topic
- Design an API Rate Limiter: solution and walkthrough
- Design a Distributed Messaging System: solution and walkthrough
- Design an Online Payment Service: solution and walkthrough
- Design a Key Value Store: solution and walkthrough

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.