Quick revision
The short answer
Collectors.toMap refuses null values: in current JDKs the two-argument form checks each value with Objects.requireNonNull, and the forms with a merge function use Map.merge, which also throws for null, so a product with a null discount causes a NullPointerException even though no product or SKU is null. We fix it by filtering nulls, mapping them to a default or Optional, or collecting with collect(HashMap::new, (m, p) -> m.put(p.sku(), p.discount()), Map::putAll); toMap also throws IllegalStateException on duplicate keys unless we give a merge function. The JSON order changed because HashMap has no defined iteration order, so if order matters we collect into a LinkedHashMap or TreeMap, or make clients not rely on it.
What to remember
In this answer, we saw that Collectors.toMap rejects null values, through Map.merge or an explicit null check in the two-argument form, which is why a null discount caused a NullPointerException; we fixed it by filtering, defaulting or collecting with a null-tolerant collect, and noted that toMap also throws on duplicate keys without a merge function. The JSON order changed because HashMap's order depends on its table size and was never defined; LinkedHashMap, TreeMap, or clients that do not rely on order fix that.
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 refuses null values: in current JDKs the two-argument form checks each value with Objects.requireNonNull, and the forms with a merge function use Map.merge, which also throws for null, so a product with a null discount causes a NullPointerException even though no product or SKU is null. We fix it by filtering nulls, mapping them to a default or Optional, or collecting with collect(HashMap::new, (m, p) -> m.put(p.sku(), p.discount()), Map::putAll); toMap also throws IllegalStateException on duplicate keys unless we give a merge function. The JSON order changed because HashMap has no defined iteration order, so if order matters we collect into a LinkedHashMap or TreeMap, or make clients not rely on it.
Why this question is asked
Turning a list into a map with a stream is so common that we rarely look at it twice, yet Collectors.toMap has stricter rules than the HashMap it produces. This question combines that hidden rule with a second, quieter problem: an innocent rewrite that changes the order of fields in an API response. Interviewers like it because both problems come from relying on behaviour that was never promised. In this answer, we will reproduce the NullPointerException, explain where it comes from, look at the fixes and the duplicate-key rule, then explain why the JSON order changed and how to make it predictable.
1Reproducing the NullPointerException
Here is a minimal version of the production code. One product has no discount, so its discount field is null. The product and its SKU are fine.
Notice the surprise. A plain HashMap is perfectly happy to store a null value; map.put("B2", null) works. So the restriction does not come from the map. It comes from the collector.
2Why toMap Rejects Null Values
Collectors.toMap was designed around Map.merge, the method that puts a value or combines it with an existing one. Map.merge treats a null value as meaning remove the entry, so it cannot store a null, and its contract says it throws NullPointerException when the value is null. The versions of toMap that take a merge function still use Map.merge directly. The two-argument version, in current JDKs, uses a faster accumulator that checks for duplicate keys itself, and it calls Objects.requireNonNull on each value to keep the same rule. Either way the effect is the same: toMap does not accept null values, whatever map it builds.
This is why the bug appeared only in production. The test data had a discount on every product, and the first real product without one failed the whole request.
3Fixing It
The right fix depends on what a missing discount means. If products without a discount should simply not appear in the map, filter them out. If missing means zero, map null to a default. If callers need to distinguish missing from zero, either keep null values with a collector that allows them, or make the absence explicit.
The third form uses the general collect(supplier, accumulator, combiner), which calls put directly, so nulls are stored like in any HashMap. Be aware of what it gives up: put silently replaces an earlier value for the same key, so duplicate SKUs would no longer be detected.
4The Duplicate-Key Rule
toMap has a second strict rule. If two elements produce the same key, the two-argument form throws IllegalStateException with a message such as Duplicate key A1 (attempted merging values 0.10 and 0.20). That is usually helpful, because two products with one SKU is a data problem. When duplicates are expected, we pass a merge function that decides which value wins.
Note that this version uses Map.merge, so it still throws for null values; combine it with a default or a filter if both rules matter.
5Why the JSON Order Changed
The second problem is that after a colleague rewrote the stream as a loop that puts into a HashMap, a JSON field, which serializes the map, showed its keys in a different order. Jackson, like most JSON libraries, writes a Map's entries in the map's own iteration order. So the JSON order is simply the HashMap's order.
A HashMap's order is not defined. It iterates bucket by bucket, and the bucket for a key depends on the key's hash and the size of the internal table. The table size depends on how the map was created and how it grew. A loop that creates new HashMap<>(products.size()) starts with a different table size than the collector's default HashMap, so the same keys land in different buckets and come out in a different order. Different data, a different number of entries, or a different JDK can reorder it too. Neither version ever promised an order; both happened to produce one.
- Build the map
toMap'sHashMap, or the loop's presizedHashMap - Keys placed in bucketsPosition depends on hash and table size
- Jackson iterates the mapWrites entries in iteration order
- Need a stable order?Do clients or tests depend on it?YesUse LinkedHashMap or TreeMapNoLeave HashMap; clients must not rely on order
4 steps in order. Play them, or step through them one at a time.
6Making the Order Predictable
If the order matters, we choose a map that defines one. A LinkedHashMap keeps insertion order, here the order of the products list; a TreeMap sorts by SKU. With toMap, the four-argument version takes a map supplier. With the null-tolerant collect, we simply pass LinkedHashMap::new.
It is also worth asking whether clients should depend on the order at all. A JSON object is defined as an unordered set of name-value pairs, so a well-behaved client looks fields up by name. If a client or a snapshot test compares raw JSON text, the safer fix may be on that side. Jackson can also sort map keys during serialization with its ORDER_MAP_ENTRIES_BY_KEYS feature, which gives a stable order without changing the map type.
7Follow-up questions
Which Map implementations allow null keys and values?
HashMap and LinkedHashMap allow one null key and any number of null values. TreeMap allows null values, but a null key throws NullPointerException with natural ordering, unless the comparator handles null. Hashtable, ConcurrentHashMap, ConcurrentSkipListMap and the Map.of family reject both null keys and null values. EnumMap allows null values but not null keys, and IdentityHashMap and WeakHashMap allow both.
Why does ConcurrentHashMap reject nulls?
Because in a concurrent map, get returning null would be ambiguous: the key might be absent, or present with a null value, and another thread could change it between a get and a containsKey. Forbidding null values removes that ambiguity.
Is collect(Collectors.toMap(...)) slower than a loop?
Not meaningfully for normal sizes. The choice should be about clarity and the rules we need, such as null handling and duplicate detection, not speed.
8Conclusion
In this answer, we saw that Collectors.toMap rejects null values, through Map.merge or an explicit null check in the two-argument form, which is why a null discount caused a NullPointerException; we fixed it by filtering, defaulting or collecting with a null-tolerant collect, and noted that toMap also throws on duplicate keys without a merge function. The JSON order changed because HashMap's order depends on its table size and was never defined; LinkedHashMap, TreeMap, or clients that do not rely on order fix that.
Open with
The NullPointerException comes from the collector, not the map. Collectors.toMap does not accept null values: the variants with a merge function use Map.merge, which throws for a null value, and the two-argument version in current JDKs does an explicit requireNonNull on each value to keep the same rule.
Then, if they want more
Some products have a null discount, so the first one fails the whole stream, even though HashMap itself could store null. The fix depends on what null means. If those products should be left out, filter them. If no discount means zero, map it to a default with requireNonNullElse.
If we really need nulls in the map, collect with HashMap::new, an accumulator that calls put, and putAll, but that silently overwrites duplicate SKUs. Also, toMap throws IllegalStateException on duplicate keys unless we give a merge function, which I usually want, because duplicate SKUs are a data problem.
For the JSON order: Jackson writes a map in its iteration order, and HashMap has no defined order; it depends on hash codes and the table size. The colleague's loop probably created the map differently, for example presized, so keys landed in different buckets. Neither version promised an order.
If order matters, I collect into a LinkedHashMap with the four-argument toMap, or a TreeMap to sort by SKU. Otherwise, clients should look fields up by name, since JSON objects are unordered.
About this answer
- Last updated
- 12 November 2026
- 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
- The Collections Framework, overview, java.util, 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 "A service converts a list of products to a map with...": https://scrivio-interview-library.netlify.app/java/collections-overview/5b1006e091/