Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

This code builds a Map with streams and fails in production with IllegalStateException: Duplicate key 17 (attempted merging values ...): products.stream().collect(Collectors.toMap(Product::categoryId, Product::name)). Another version fails with NullPointerException. Explain both and fix them.

Collectors.toMap(keyMapper, valueMapper) throws IllegalStateException when two elements produce the same key, because without a merge function it has no rule for choosing a value; categories have many products, so category 17 appears twice. The NullPointerException comes from a null value, such as a product with no name, because toMap refuses null values and its merge-based versions call Map.merge, which throws on null. We fix the first by passing a merge function or, better for one-to-many data, using groupingBy, and the second by filtering or replacing nulls, and we pass a map supplier such as LinkedHashMap::new or TreeMap::new when order matters.

Why this question is asked

Collectors.toMap looks like the obvious way to turn a list into a map, and it works in every test where the data happens to have unique keys and no nulls. Then production data arrives with a category that has two products, or a product without a name, and the job fails. Interviewers ask this question because both failures come from rules that are easy to miss in the Javadoc, and because the right fix depends on what the data really means. In this answer, we will recap what toMap does, reproduce the duplicate key failure and fix it, reproduce the null failure and fix it, decide when groupingBy is the better tool, and look at ordering and the immutable map factories, which have similar rules.

1A Quick Recap of Collectors.toMap

Collectors.toMap takes a key mapper and a value mapper, two functions that turn each stream element into a key and a value. By default it collects into a HashMap. There are three overloads: with two arguments, with a third argument called the merge function, which decides what to do when two elements map to the same key, and with a fourth argument called the map supplier, which decides which Map implementation to create.

With only two arguments, toMap assumes that keys are unique. It does not silently keep the first or last value, because either choice could hide a data problem. Instead it throws.

2Reproducing the Duplicate Key Failure

Here is a small data set that looks harmless, where categoryId is not unique.

Java
record Product(long id, int categoryId, String name) {}
List<Product> products = List.of(
new Product(1, 17, "Kettle"),
new Product(2, 17, "Toaster"),
new Product(3, 22, "Lamp"));
products.stream().collect(Collectors.toMap(Product::categoryId, Product::name));
// IllegalStateException: Duplicate key 17 (attempted merging values Kettle and Toaster)

The message names the key and both values (the detailed message format comes from Java 9 onwards). The code assumed a category has one product, and the data disagrees. Before fixing it, we have to decide what the map should mean. If we want one name per category, we choose which one. If we want all names per category, the map's value type should be a collection.

3Fix 1: A Merge Function

The third argument receives the existing value and the new value for the same key and returns the value to keep.

Java
Map<Integer, String> firstName = products.stream()
.collect(Collectors.toMap(Product::categoryId, Product::name, (a, b) -> a));
firstName; // {17=Kettle, 22=Lamp}: keeps the first
Map<Integer, String> joined = products.stream()
.collect(Collectors.toMap(Product::categoryId, Product::name, (a, b) -> a + "," + b));
joined; // {17=Kettle,Toaster, 22=Lamp}

Notice that (a, b) -> a is a decision, not a fix: it silently drops Toaster. That is right only if any product of the category will do, for example to pick a sample. Joining strings works but loses structure, which leads to the better fix.

4Fix 2: groupingBy for One-to-Many Data

When one key has many values by nature, as categories and products do, the map should say so with a collection value. groupingBy builds a Map<K, List<T>>, and a downstream collector shapes each list.

Java
Map<Integer, List<String>> namesByCategory = products.stream()
.collect(Collectors.groupingBy(Product::categoryId,
Collectors.mapping(Product::name, Collectors.toList())));
namesByCategory; // {17=[Kettle, Toaster], 22=[Lamp]}
Step throughChoosing the collector
  1. Can one key have several values?
    YesgroupingBy with a downstream collectorNotoMap
  2. Is a duplicate key a data error?
    YestoMap with two arguments, let it throwNotoMap with a merge function
  3. Can a value be null?
    Yesfilter or replace nulls firstNocollect
  4. Does order matter?
    Yespass LinkedHashMap::new or TreeMap::newNodefault HashMap

4 steps in order. Play them, or step through them one at a time.

This version cannot fail on duplicates, because duplicates are the point. Choosing between toMap and groupingBy is really a question about the domain: is the relationship one-to-one or one-to-many? If it should be one-to-one and is not, throwing is often the correct behaviour, and we should fix the data or the key instead of hiding the error with a merge function.

5Reproducing and Fixing the NullPointerException

The second failure has a different cause: a value mapper that returns null.

Java
List<Product> withGap = List.of(new Product(1, 17, "Kettle"), new Product(4, 30, null));
withGap.stream().collect(Collectors.toMap(Product::id, Product::name));
// NullPointerException: product 4 has no name
withGap.stream().collect(Collectors.toMap(Product::id, Product::name, (a, b) -> a));
// NullPointerException too: this overload calls Map.merge, which rejects null values

HashMap itself allows null values, so this surprises people. The two-argument toMap checks each value for null explicitly, and the overloads with a merge function call Map.merge, whose contract says a null value throws NullPointerException. Either way, a null value cannot get into the map through toMap.

The fix depends on what a missing name means. If such products should be left out, filter them with .filter(p -> p.name() != null). If they should appear with a placeholder, map the value first, for example p -> Objects.requireNonNullElse(p.name(), "(unnamed)"). If the value is truly optional, an Optional<String> value makes the absence explicit. Storing null in a map is rarely what we want, because get() then cannot tell a missing key from a null value.

6Choosing the Map Type, and the Immutable Factories

toMap and groupingBy return a HashMap by default, so their iteration order is not defined. When order matters, we pass a supplier: LinkedHashMap::new keeps the encounter order of the stream, and TreeMap::new sorts by key. With toMap, the supplier is the fourth argument, so we must also pass a merge function; with groupingBy, it is the middle argument.

The same strictness appears in the immutable factories. Map.of and Map.ofEntries throw IllegalArgumentException on a duplicate key, and Map.of, Map.ofEntries and Map.copyOf throw NullPointerException on a null key or value. So a pipeline that ends in Map.copyOf has the same null rule as toMap.

Java
Map<Integer, String> ordered = products.stream()
.collect(Collectors.toMap(Product::categoryId, Product::name, (a, b) -> a, TreeMap::new));
ordered; // {17=Kettle, 22=Lamp}, sorted by key
Map.of(1, "a", 1, "b"); // IllegalArgumentException: duplicate key: 1
Map.of(1, null); // NullPointerException

7Follow-up questions

Why does toMap not just keep the last value like put does?

Because silently replacing a value would hide data problems. A stream of records with duplicate keys usually means an assumption is wrong, and failing loudly at that point is safer than producing a map that quietly lost data. If we really want last-wins, (a, b) -> b says so explicitly.

How would you collect into a map that allows null values?

Use collect with three functions: products.stream().collect(HashMap::new, (m, p) -> m.put(p.id(), p.name()), Map::putAll). This uses HashMap.put, which accepts null values and keeps the last value on duplicates. It is legal, but we should be sure that null values are really what we want before doing it.

8Conclusion

In this answer, we saw that Collectors.toMap without a merge function throws IllegalStateException on duplicate keys, and that it rejects null values, through an explicit check in the two-argument form and through Map.merge in the forms with a merge function. A merge function such as (a, b) -> a or (a, b) -> a + "," + b resolves duplicates, but groupingBy is the right tool for one-to-many data. We filter or replace null values, pass LinkedHashMap::new or TreeMap::new when order matters, and remember that Map.of and Map.copyOf are just as strict about duplicates and nulls.

What to say in the interviewAbout 90 seconds aloud

Open with

The IllegalStateException happens because toMap with only a key mapper and a value mapper assumes keys are unique. Category 17 has more than one product, and without a merge function toMap has no rule for choosing, so it throws and, since Java 9, names the key and both values.

Then, if they want more

I would first ask what the map should mean. If a category really has many products, toMap is the wrong collector, and I would use groupingBy with mapping to a list of names.

If I do want one value per key, I pass a merge function, like a, b returns a to keep the first, or concatenate them, but I treat that as a business decision, not a quick fix. The NullPointerException comes from a null value, for example a product with no name.

HashMap accepts null values, but toMap does not: the two-argument version checks values for null, and the versions with a merge function call Map.merge, which throws on null. So I would filter those products out, or map the null to a placeholder or an Optional.

If order matters, I pass a map supplier such as LinkedHashMap::new or TreeMap::new as the fourth argument. I would also mention that Map.of rejects duplicates, and Map.of and Map.copyOf reject nulls, so the same rules apply there.

About this answer

Last updated
12 November 2026
Versions it names
Java 9
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.
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 "This code builds a Map with streams and fails in production with IllegalStateException...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/c573e6bd04/