Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Given List<Employee> with getEmail(), find the emails that appear more than once. Then a colleague converts the list to a Map with Collectors.toMap(Employee::getEmail, e -> e) and gets IllegalStateException. Explain and fix both.

To find emails that appear more than once, the clean way is to count them with groupingBy(Function.identity(), counting()) and keep the keys whose count is greater than 1; a HashSet with filter(e -> !seen.add(e)) also works on a sequential stream, but it relies on a side effect. The colleague's Collectors.toMap(Employee::getEmail, e -> e) throws IllegalStateException because two employees share an email and toMap refuses duplicate keys unless we pass a merge function such as (a, b) -> a. toMap also throws NullPointerException for null values, and the four-argument form with LinkedHashMap::new keeps encounter order.

Why this question is asked

Converting a list into a map by some key is one of the most common things we do with streams, and duplicate keys are one of the most common surprises in production data: two customer records with the same email, two products with the same SKU after a bad import. Interviewers ask this question to see whether we know what the collectors promise and how they fail, not just how to call them. In this answer, we will find the duplicates in two ways and see why one is preferred, reproduce the toMap exception, fix it with a merge function, deal with null values and ordering, and then explain why the HashSet trick breaks on parallel streams.

1A Quick Recap of the Collectors Involved

A collector tells a stream how to gather its elements into a result. Collectors.groupingBy(classifier, downstream) puts elements into groups by a key and then reduces each group with the downstream collector; with counting() as the downstream, each group becomes a Long count. Collectors.toMap(keyMapper, valueMapper) builds a map where each element contributes one entry. The difference matters here: groupingBy expects many elements per key, while toMap, in its two-argument form, expects exactly one.

2Finding the Duplicate Emails

The quick version keeps a set of emails seen so far and lets through every email that was already in it. Set.add returns false when the element is already present, so !seen.add(e) is true for second and later occurrences.

Java
List<Employee> employees = List.of(
new Employee("Ana", "ana@x.com"), new Employee("Ben", "ben@x.com"),
new Employee("Ana B", "ana@x.com"), new Employee("Cy", "cy@x.com"),
new Employee("Ben K", "ben@x.com"), new Employee("Ana C", "ana@x.com"));
// Side-effect version: works on a sequential stream
Set<String> seen = new HashSet<>();
Set<String> dups1 = employees.stream()
.map(Employee::getEmail)
.filter(e -> !seen.add(e)) // true from the second occurrence on
.collect(Collectors.toSet()); // [ana@x.com, ben@x.com]
// Counting version: no shared state
Set<String> dups2 = employees.stream()
.collect(Collectors.groupingBy(Employee::getEmail, Collectors.counting())) // {ana=3, ben=2, cy=1}
.entrySet().stream()
.filter(en -> en.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet()); // [ana@x.com, ben@x.com]

Both give the same answer here. The counting version is cleaner because each step is a pure function of its input: nothing outside the pipeline is changed, so it is easy to reason about, gives us the counts for free, which are handy for a report, and stays correct if someone later adds parallel(). The side-effect version changes a set that lives outside the stream, which the Stream documentation advises against.

Two real-data details are worth adding. Emails often differ only in case, so we normalize the key with e.getEmail().toLowerCase(Locale.ROOT) if the business treats Ana@x.com and ana@x.com as the same address. And groupingBy throws NullPointerException with a message like element cannot be mapped to a null key if an employee has no email, so we filter those out first or group them under a placeholder.

3Why toMap Throws IllegalStateException

Now the colleague's code. The two-argument toMap promises that each key appears once, and when it sees a second element with the same key it stops with an exception instead of silently picking one.

Java
Map<String, Employee> byEmail = employees.stream()
.collect(Collectors.toMap(Employee::getEmail, e -> e));
// java.lang.IllegalStateException: Duplicate key ana@x.com
// (attempted merging values Employee[name=Ana, ...] and Employee[name=Ana B, ...])

The message names the key and, in current JDKs, both values, which makes it easy to find the bad data. The design is deliberate: if two employees share an email, the code has to decide which one wins, and toMap will not guess. Notice that a plain loop with map.put would silently keep the last employee and hide the data problem.

4Fix: Making the Merge Decision Explicit

So the fix is to make the decision explicit with the three-argument form, whose third argument is a merge function that receives the existing value and the new one and returns the value to keep.

Java
Map<String, Employee> keepFirst = employees.stream()
.collect(Collectors.toMap(Employee::getEmail, e -> e, (first, second) -> first));
// {ana@x.com=Ana, ben@x.com=Ben, cy@x.com=Cy}
Map<String, List<Employee>> all = employees.stream()
.collect(Collectors.groupingBy(Employee::getEmail));
// {ana@x.com=[Ana, Ana B, Ana C], ben@x.com=[Ben, Ben K], cy@x.com=[Cy]}
Which collector for which situation
NeedCollectorOn duplicate keys
Exactly one value per keytoMap(k, v)IllegalStateException
One value, pick a winnertoMap(k, v, (a, b) -> a)merge function decides
One value, keep ordertoMap(k, v, merge, LinkedHashMap::new)merge function decides
All values per keygroupingBy(k)kept in a List
How many per keygroupingBy(k, counting())counted as Long

(a, b) -> a keeps the first employee in encounter order, and (a, b) -> b keeps the last. If losing the other records is not acceptable, groupingBy keeps all of them in a list per key. Which one is right is a business question, and in a code review we would ask it rather than reach for (a, b) -> a by reflex.

5Null Values and Encounter Order

toMap has a second surprise: it does not accept null values. The two-argument form checks each value with Objects.requireNonNull, and the forms with a merge function build the map with Map.merge, which also throws NullPointerException for a null value. So if the value mapper were Employee::getManager and some employees have no manager, the collection fails even though HashMap itself allows null values. We either filter those elements out, map null to an explicit placeholder such as Optional, or build the map with a plain loop or a custom collector, for example Collector.of(HashMap::new, (m, e) -> m.put(k(e), v(e)), (m1, m2) -> { m1.putAll(m2); return m1; }).

The result of toMap is currently a HashMap, so its iteration order has nothing to do with the order of the list. When order matters, for example for a report or a JSON response, the four-argument form takes a map supplier: toMap(Employee::getEmail, e -> e, (a, b) -> a, LinkedHashMap::new) keeps the encounter order of first appearance. TreeMap::new would sort by email instead.

6Follow-up questions

Why is the HashSet trick unsafe with parallel streams?

Because HashSet is not thread-safe. In a parallel stream, filter runs on several ForkJoinPool threads at once, so concurrent add calls can corrupt the set's internal table, lose entries or report a duplicate wrongly, and the result can change from run to run. It also breaks the stream rule that behavioural parameters should be stateless. Swapping in ConcurrentHashMap.newKeySet() makes the set safe, but which occurrence counts as the first becomes arbitrary, so the counting version with groupingBy remains the right answer: each thread builds its own partial maps, and the stream merges them safely.

Does toMap keep the first or the last value when I pass a merge function?

Neither, by itself: it calls the merge function with the existing value and the new one, in encounter order for a sequential stream, and keeps whatever the function returns. (a, b) -> a keeps the first and (a, b) -> b keeps the last. On a parallel stream with an ordered source, toMap still respects encounter order when it combines partial results, but toConcurrentMap does not, so first and last lose their meaning there.

What does Collectors.toMap return, and can I modify it?

The specification only promises a Map with no guarantees on type, mutability or thread safety. In current JDKs it is a HashMap, so it happens to be mutable, but code should not rely on that. If I need a specific type I pass the map supplier, and if I need an unmodifiable map I use Collectors.toUnmodifiableMap, which also rejects duplicate keys and null values.

7Conclusion

In this answer, we found duplicate emails in two ways: a HashSet with filter(e -> !seen.add(e)), which works sequentially but depends on a side effect, and groupingBy with counting(), which is pure and gives the counts too. We saw that Collectors.toMap throws IllegalStateException on duplicate keys by design, and that a merge function such as (a, b) -> a, or groupingBy when every record matters, makes the decision explicit. toMap also rejects null values, and the four-argument form with LinkedHashMap::new keeps encounter order.

What to say in the interviewAbout 100 seconds aloud

Open with

For the duplicates, I would count rather than track state. I collect the emails with groupingBy, using the email as the key and counting as the downstream collector, which gives a map from email to a Long count, then I stream its entries, keep those with a count above one, and collect the keys.

Then, if they want more

The shortcut with a HashSet and filter not seen.add also works on a sequential stream, because add returns false for an email already seen, but it mutates state outside the pipeline, so it breaks if someone adds parallel. I would also normalise the email with toLowerCase and Locale.ROOT, and filter out null emails, because groupingBy rejects null keys.

The colleague's toMap fails because two-argument toMap requires unique keys, and when it sees the same email twice it throws IllegalStateException saying duplicate key, naming the key. That is deliberate, it will not guess which employee should win.

The fix is the three-argument form with a merge function, for example a, b returns a to keep the first, or groupingBy if we need all the employees per email, and which one is right is a business decision I would ask about.

Two more things I mention: toMap also throws NullPointerException for null values, even though HashMap allows them, so I filter or use a placeholder. And the default map is a HashMap with no useful order, so if order matters I use the four-argument version with LinkedHashMap::new.

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 official documentation for the version you use. 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 "Given List<Employee> with getEmail(), find the emails that appear more than once. Then a...": https://scrivio-interview-library.netlify.app/java/coding-problems/cc6fd0268f/