Java
NullPointerException
Collectors.toMap
Programming Errors
Data Handling

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:

java
Map<String, String> result = people.stream()
    .collect(Collectors.toMap(Person::name, Person::email));

But if any person's email is null, this throws:

text
java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:209)
    at java.base/java.util.stream.Collectors.lambda$uniqKeysMapAccumulator$1(Collectors.java:180)

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:

java
1import java.util.*;
2import java.util.stream.Collectors;
3
4public class ToMapNullDemo {
5    record Person(String name, String email) {}
6
7    public static void main(String[] args) {
8        List<Person> people = List.of(
9            new Person("Alice", "[email protected]"),
10            new Person("Bob", null),          // null value triggers NPE
11            new Person("Carol", "[email protected]")
12        );
13
14        // This throws NullPointerException
15        Map<String, String> emails = people.stream()
16            .collect(Collectors.toMap(Person::name, Person::email));
17    }
18}

Solution 1: filter out null values

When entries with null values should simply be left out, filtering is the cleanest approach:

java
Map<String, String> emails = people.stream()
    .filter(p -> p.email() != null)
    .collect(Collectors.toMap(Person::name, Person::email));

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:

java
Map<String, String> emails = people.stream()
    .filter(p -> p.name() != null && p.email() != null)
    .collect(Collectors.toMap(Person::name, Person::email));

Solution 2: substitute a default value

When the map must contain every key, replace nulls with a sentinel before collecting:

java
1Map<String, String> emails = people.stream()
2    .collect(Collectors.toMap(
3        Person::name,
4        p -> p.email() != null ? p.email() : ""
5    ));

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.

java
1// Using a descriptive sentinel
2Map<String, String> emails = people.stream()
3    .collect(Collectors.toMap(
4        Person::name,
5        p -> Objects.requireNonNullElse(p.email(), "N/A")
6    ));

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:

java
1Map<String, String> emails = people.stream().collect(
2    HashMap::new,
3    (map, p) -> map.put(p.name(), p.email()),
4    HashMap::putAll
5);

Result: {[email protected], Bob=null, [email protected]}

This works because HashMap.put accepts null values. The three arguments are:

  1. Supplier: creates the result container (HashMap::new).
  2. Accumulator: adds each element to the container.
  3. Combiner: merges two containers during parallel execution.

Extracting a reusable utility

If the pattern shows up often, extract it:

java
1public static <T, K, V> Collector<T, ?, Map<K, V>> toNullableMap(
2    Function<T, K> keyMapper,
3    Function<T, V> valueMapper
4) {
5    return Collector.of(
6        HashMap::new,
7        (map, element) -> map.put(keyMapper.apply(element), valueMapper.apply(element)),
8        (left, right) -> { left.putAll(right); return left; }
9    );
10}
11
12// Usage
13Map<String, String> emails = people.stream()
14    .collect(toNullableMap(Person::name, Person::email));

Duplicate keys are a separate failure

Even with nulls handled, toMap throws IllegalStateException if two elements produce the same key:

text
java.lang.IllegalStateException: Duplicate key Alice

The three-argument form of toMap takes a merge function to resolve conflicts:

java
1Map<String, String> emails = people.stream()
2    .filter(p -> p.email() != null)
3    .collect(Collectors.toMap(
4        Person::name,
5        Person::email,
6        (existing, replacement) -> existing  // keep the first value
7    ));

Common merge strategies:

java
1// Keep the first value
2(existing, replacement) -> existing
3
4// Keep the last value
5(existing, replacement) -> replacement
6
7// Concatenate
8(existing, replacement) -> existing + ", " + replacement
9
10// Throw on conflict (default behavior, made explicit)
11(existing, replacement) -> {
12    throw new IllegalStateException("Duplicate key");
13}

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:

java
1// Here Person also has a department: record Person(String name, String department, String email) {}
2
3// toMap with merge: last writer wins (lossy)
4Map<String, String> lastEmailByDept = people.stream()
5    .filter(p -> p.email() != null)
6    .collect(Collectors.toMap(
7        Person::department,
8        Person::email,
9        (a, b) -> b
10    ));
11
12// groupingBy: all values preserved
13Map<String, List<String>> emailsByDept = people.stream()
14    .filter(p -> p.email() != null)
15    .collect(Collectors.groupingBy(
16        Person::department,
17        Collectors.mapping(Person::email, Collectors.toList())
18    ));

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

ApproachNull values in result?Duplicate key handlingReadability
filter + toMapNo (excluded)Throws by defaultHigh
Default substitution + toMapNo (replaced)Throws by defaultHigh
Manual collect with HashMapYesLast writer winsMedium
Custom toNullableMap utilityYesConfigurableHigh (after initial definition)
groupingByYes (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."


Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data 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.

Practice algorithms