Quick revision
The short answer
Collectors.toMap(keyMapper, valueMapper) without a merge function throws IllegalStateException: Duplicate key as soon as two elements produce the same key, so we pass a merge function such as (a, b) -> a to keep the first. It throws NullPointerException when a value is null, because it explicitly rejects null values and the versions with a merge function rely on Map.merge, which does not accept them. We filter out nulls or collect another way if nulls must be kept, and use the four-argument toMap to choose a map type such as LinkedHashMap::new.
What to remember
In this answer, we saw why Collectors.toMap throws two different exceptions. Without a merge function it refuses duplicate keys with IllegalStateException: Duplicate key, and we fix that by passing a merge function such as (a, b) -> a, or by using groupingBy if all duplicates matter. It throws NullPointerException for null values because it rejects them explicitly and relies on Map.merge, so we filter nulls out, replace them, or collect with put. The four-argument form lets us choose the map type, such as LinkedHashMap::new to keep input order.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Collectors.toMap(keyMapper, valueMapper) without a merge function throws IllegalStateException: Duplicate key as soon as two elements produce the same key, so we pass a merge function such as (a, b) -> a to keep the first. It throws NullPointerException when a value is null, because it explicitly rejects null values and the versions with a merge function rely on Map.merge, which does not accept them. We filter out nulls or collect another way if nulls must be kept, and use the four-argument toMap to choose a map type such as LinkedHashMap::new.
Why this question is asked
Turning a list into a lookup map is everyday code: users by email, products by SKU, settings by name. Collectors.toMap looks like the obvious tool, and it works until the data contains a duplicate or a null, which in production it eventually does. Interviewers ask about both exceptions because each one exposes a design decision in the collector that many developers never noticed. In this answer, we will recap the toMap overloads, reproduce the duplicate key error and fix it with a merge function, reproduce the NullPointerException and see where it comes from, and finish with choosing the map type.
1A Quick Recap of toMap
Collectors.toMap comes in three forms. The two-argument form takes a key mapper and a value mapper, functions that compute the key and the value for each element. The three-argument form adds a merge function, which decides what to do when two elements produce the same key. The four-argument form adds a map supplier, which chooses the Map implementation; without it the result is a HashMap.
We will use a small User record for the examples: record User(String email, String nickname).
2Reproducing the Duplicate Key Error
The two-argument form assumes every key is unique. If two users share an email, perhaps because the data has the same person twice or emails differ only in case and were normalised, the collector does not guess which one we want. It fails.
Notice that since Java 9 the message names both the key and the two values, which makes the cause easy to find. The design choice is deliberate: silently keeping the first or the last value could hide a data problem, so the collector forces us to decide.
3Fix: Provide a Merge Function
The three-argument form takes a merge function that receives the existing value and the new one and returns the value to keep.
- Compute key and value
keyMapper,valueMapper - Is the value null?YesNullPointerExceptionNoContinue
- Is the key already in the map?YesMerge or failNoPut the new entry
- Was a merge function given?YesKeep what it returnsNoIllegalStateException: Duplicate key
4 steps in order. Play them, or step through them one at a time.
Which merge function is right is a business question, not a technical one. Keeping the first is common when the input is ordered by priority; keeping the most recent is common for updates. If duplicates should never happen, keeping the exception and fixing the data may be the right answer. And if all duplicates matter, groupingBy is the better collector.
4Why a Null Value Throws NullPointerException
The second failure happens when the value mapper returns null, for example when we map emails to nicknames and some users have no nickname.
The reason is in how toMap stores values. The versions with a merge function are built on Map.merge(key, value, function), and Map.merge treats a null value as forbidden, because in its contract null means remove the entry. The two-argument version, since Java 9, checks each value with Objects.requireNonNull before inserting it, so it fails the same way. So it is not HashMap rejecting the null, HashMap would accept it with put; it is toMap's contract. A null key, by contrast, is accepted when the target map is a HashMap, but rejected if we choose a map such as TreeMap or ConcurrentHashMap.
5Fixes for Null Values
If users without a nickname should not be in the map, the simplest fix is to filter them out first. If they should be present, we must either replace null with a real value, such as an empty string or an Optional, or collect with an approach that uses put directly.
Notice the trade-off in the second version: by using put, we accept nulls but also lose the duplicate check, so a later duplicate silently replaces an earlier one. Storing nulls in a map is usually a smell anyway, because get() then cannot tell a missing key from a null value.
6Choosing the Map Type With the Four-Argument Form
The result of toMap is a HashMap, which has no defined iteration order. If we want to keep the order of the input, for example to show users in the order they were listed, we use the four-argument form with LinkedHashMap::new. TreeMap::new gives keys in sorted order.
Note that the four-argument form requires a merge function too, so we must decide on duplicates whenever we choose the map type.
7Follow-up questions
Is toUnmodifiableMap different in how it treats duplicates and nulls?
Collectors.toUnmodifiableMap, added in Java 10, also throws IllegalStateException on duplicate keys unless a merge function is given, and it rejects both null keys and null values with NullPointerException. Its result cannot be modified.
What about toConcurrentMap with parallel streams?
toConcurrentMap collects into a ConcurrentHashMap and can let several threads insert at once, which can be faster for large parallel streams. ConcurrentHashMap rejects null keys and null values, so the null rules are even stricter.
How do I find which elements are duplicates before deciding on a merge function?
Group and filter: users.stream().collect(groupingBy(User::email, counting())) and then keep entries whose count is greater than one. This is a quick way to inspect the data before choosing to keep the first, the last or to fail.
8Conclusion
In this answer, we saw why Collectors.toMap throws two different exceptions. Without a merge function it refuses duplicate keys with IllegalStateException: Duplicate key, and we fix that by passing a merge function such as (a, b) -> a, or by using groupingBy if all duplicates matter. It throws NullPointerException for null values because it rejects them explicitly and relies on Map.merge, so we filter nulls out, replace them, or collect with put. The four-argument form lets us choose the map type, such as LinkedHashMap::new to keep input order.
Open with
The first exception comes from the two-argument toMap, which assumes keys are unique. When two users have the same email, it doesn't guess which one to keep; it throws IllegalStateException: Duplicate key, and since Java 9 the message shows the key and both values.
Then, if they want more
The fix is the three-argument version with a merge function: a comma b arrow a keeps the first, a comma b arrow b keeps the last, and which one is right is a business decision. If we need every duplicate, groupingBy by email is the better collector.
The NullPointerException happens when the value mapper returns null, say a user with no nickname. toMap doesn't allow null values: the merge-function versions use Map merge, where a null value is forbidden because it means remove, and the two-argument version checks values with requireNonNull. HashMap itself would accept the null with put; it's the collector's contract.
To fix it, I filter out users with a null value first, or replace null with a real value, or, if I truly need nulls, collect with HashMap new and put, accepting that I lose the duplicate check.
And the four-argument toMap lets me pick the map, for example LinkedHashMap colon colon new to keep input order, or TreeMap for sorted keys; it also requires a merge function, so I always have to decide about duplicates.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9, Java 10
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.stream, package documentation, java.util.function, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Collectors.toMap(User::email, u -> u) throws IllegalStateException: Duplicate key....": https://scrivio-interview-library.netlify.app/java/streams/ab3554f1a9/