Your Collectors.toMap call passed every test and threw in production. What did the code assume, and what are your options?
It assumed unique keys and non-null values. Collectors.toMap throws IllegalStateException on a duplicate key and NullPointerException on a null value, so supply a merge function that encodes a real rule, use groupingBy when duplicates are legitimate, or collect into a HashMap directly if nulls must survive.
Answer
Short answer
The code assumed two things about production data. Collectors.toMap throws IllegalStateException the first time two elements map to the same key, and NullPointerException the first time a value mapper returns null. Test fixtures usually have unique keys and every field filled in, so neither assumption gets exercised. The fix is a decision, not a patch: a merge function that says which value wins, groupingBy when several values per key are correct, or a direct HashMap collection when nulls must be kept.
Was this answer helpful?
Likely follow-ups
- On JDK 8 the duplicate-key message prints a value, not the key. How would that have misled your production investigation?
- Why does a HashMap that happily stores null values still make toMap throw on one?
- What does a merge function of (a, b) -> a silently do to data, and when is that acceptable?
- How would you write a test that would have caught this before the release?
Related questions
- Adding a second LEFT JOIN doubled the revenue figure on a report. Explain what happened and write the correct query.mediumAlso on null-handling4 min
- Write a query returning the second-highest salary in each department, then tell me what it does when two people tie for the top.mediumAlso on null-handling3 min
- You put logging in peek() to debug a stream, and nothing prints once the pipeline ends in count(). Is the stream broken?mediumAlso on streams4 min
- Why would you stream a large file rather than read it into memory, and what is backpressure?mediumAlso on streams4 min