BackendBench
Coffee
Spot the Bug #82

A map that refuses duplicate names

A medium Java puzzle in the streams and lambdas family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumStreams and lambdasbuggy line: 9

Highlighted: line 9. Play this one as a puzzle without the answer.

What is wrong

Collectors.toMap throws IllegalStateException when two elements produce the same key. The message "Duplicate key ann" appears only when the data contains a duplicate, so the code works in tests with distinct names.

The fix

.collect(Collectors.toMap(User::name, User::id, (a, b) -> b)) // or groupingBy to keep all

How to avoid it next time

Always supply a merge function to toMap unless keys are guaranteed to be unique, or use groupingBy.

Want the background? Read Collectors: groupingBy, toMap, joining in the Java concepts library.

About streams and lambdas

Streams are single-use and lazy, and lambdas can only capture effectively final variables. Side effects inside stream pipelines and parallel streams over shared state are frequent sources of surprise.

In code review: Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #81#83 โ†’

Frequently asked questions

What is the bug in "A map that refuses duplicate names"?

Collectors.toMap throws IllegalStateException when two elements produce the same key. The message "Duplicate key ann" appears only when the data contains a duplicate, so the code works in tests with distinct names. The faulty line is line 9: Map byName = users.stream().collect(Collectors.toMap(User::name, User::id));

How do I fix it?

Replace it with: .collect(Collectors.toMap(User::name, User::id, (a, b) -> b)) // or groupingBy to keep all. Always supply a merge function to toMap unless keys are guaranteed to be unique, or use groupingBy.

How do I catch streams and lambdas in code review?

Check whether a stream variable is used twice, whether the terminal operation is present, and whether any lambda mutates outside state.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need