Quick revision
The short answer
stream().distinct() keeps the first occurrence in encounter order on a sequential ordered stream, but it compares whole records with equals, so it cannot deduplicate by email alone. To keep the first record per email in order, we use a loop with a seen set of normalised emails, or collect with toMap(email, r -> r, (a, b) -> a, LinkedHashMap::new) and take the values. Pre-sizing the collections avoids repeated resizing, for example with LinkedHashSet.newLinkedHashSet(n) on Java 19 and later, and emails must be normalised for case and whitespace first. In parallel, keeping encounter order makes distinct and similar collectors expensive, and unordered() helps only if order does not matter, which here it does.
What to remember
In this answer, we saw that distinct() keeps the first occurrence in order on a sequential stream, but compares whole objects, so it cannot deduplicate by email. A loop with a seen set of normalised emails, or toMap with a keep-first merge function and LinkedHashMap::new, keeps the first record per email in original order. Parallel ordered deduplication is expensive, and unordered() only helps if order does not matter. Pre-sizing with the Java 19 factories avoids resizes, and emails must be normalised for case and whitespace before comparison.
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.
stream().distinct() keeps the first occurrence in encounter order on a sequential ordered stream, but it compares whole records with equals, so it cannot deduplicate by email alone. To keep the first record per email in order, we use a loop with a seen set of normalised emails, or collect with toMap(email, r -> r, (a, b) -> a, LinkedHashMap::new) and take the values. Pre-sizing the collections avoids repeated resizing, for example with LinkedHashSet.newLinkedHashSet(n) on Java 19 and later, and emails must be normalised for case and whitespace first. In parallel, keeping encounter order makes distinct and similar collectors expensive, and unordered() helps only if order does not matter, which here it does.
Why this question is asked
Deduplication sounds trivial until the data is large, the duplicates are defined by one field rather than the whole object, and the order must be preserved. With 5 million customer records, the wrong approach can use gigabytes of memory, run slowly in parallel, or silently treat "Ann@Example.com " and "ann@example.com" as different people. Interviewers ask this question to see whether we know what each tool actually compares, how ordering affects streams, and how to size collections for a large input. In this answer, we will recap what distinct does, see why it is the wrong tool here, write the loop and collector versions, look at the parallel case, and finish with sizing and normalisation.
1A Quick Recap of distinct()
Stream.distinct() returns a stream without duplicates, where a duplicate means equal according to equals. On a sequential stream from a List, which is ordered, it keeps the first occurrence of each element and preserves encounter order, the order in which elements come from the source. Internally it does this by remembering the elements it has already seen in a set and passing an element on only when it is new.
So distinct is fine when two records are duplicates exactly when they are equal objects. Our requirement is different: two records are duplicates when they have the same email, even if their names or ids differ.
Overriding equals on Customer to compare only email would make distinct work, but it would also change equality everywhere else the class is used, which is a high price for one operation. We need to deduplicate by a key without changing the record.
2The Loop With a Seen Set
The clearest solution is a single pass that remembers which emails it has already kept.
- Take the next record
- Normalise its emailstrip, lowercase with
Locale.ROOT - seen.add(email) returned true?YesFirst time: append record to outputNoDuplicate: skip it
- More records?YesBack to the first stepNoReturn output in original order
4 steps in order. Play them, or step through them one at a time.
Notice that seen only needs to be a HashSet, not a LinkedHashSet, because the order lives in the output list. The set stores 5 million short strings rather than whole records, and Set.add returning false for an existing element gives us the check and the insert in one call.
3The Collector Version
With streams, we can express the same thing as a map from email to the first record, using a LinkedHashMap so the first insertion order is kept.
The merge function (first, later) -> first keeps the existing record when a duplicate arrives, and because a LinkedHashMap does not move an existing key on update, each email stays in the position of its first occurrence. To pre-size it, we can pass () -> LinkedHashMap.newLinkedHashMap(rows.size()) as the supplier. A LinkedHashSet of whole records, by contrast, would have the same limitation as distinct, because it compares the records with equals.
4What Changes in Parallel
Running the dedupe in parallel sounds attractive for 5 million records, but order makes it hard. In a parallel ordered stream, distinct must still return the first occurrence in encounter order, so it cannot let each thread decide independently; the JDK implementation has to collect partial results and combine them while respecting order, which uses extra memory and often removes most of the speedup. The same is true for a toMap with a LinkedHashMap supplier, because each thread builds its own map and they are merged in order.
Calling unordered() lets distinct use a shared concurrent set and keep whichever occurrence a thread sees first, which is much cheaper. But then we no longer keep the first occurrence or the original order, and the requirement says we must. So here the honest answer is that a sequential single pass is the right choice. For 5 million records, hashing and storing 5 million short strings takes well under a second or two on a modern machine; the input loading usually dominates. If profiling ever showed otherwise, we could split the work by email hash into partitions, dedupe each partition in parallel while tracking original positions, and merge by position, but that complexity is rarely justified.
| Approach | Dedupes by email? | Keeps first and order? | Cost |
|---|---|---|---|
distinct() | no, whole record | yes, sequential | set of whole records |
LinkedHashSet of records | no, whole record | yes | set of whole records |
| Loop with seen set | yes | yes | set of emails plus output list |
toMap with LinkedHashMap | yes | yes | one map of email to record |
parallel + unordered() | depends | no | cheaper, but breaks the requirement |
5Sizing and Normalisation
Two details decide whether the result is fast and correct. First, sizing: a default HashSet starts with 16 buckets and doubles each time it passes 75% full, so growing to hold 5 million keys means about 19 resizes, each rehashing every entry so far. HashSet.newHashSet(n), LinkedHashSet.newLinkedHashSet(n) and the matching map factories, all added in Java 19, take the number of elements we expect and compute the capacity for us. The older constructor new HashSet<>(n) takes an initial capacity, not an element count, so the set still resizes once the count passes 75% of that capacity after rounding to a power of two; the factories do that arithmetic for us.
Second, normalisation: emails from forms and imports carry surrounding spaces and mixed case. strip() removes whitespace, and toLowerCase(Locale.ROOT) lowercases without the surprises of the default locale, such as Turkish dotted and dotless i. The local part of an email is technically case-sensitive by the standard, but almost every real system treats addresses case-insensitively, so lowercasing is the usual business rule; we should confirm it with the product owner rather than assume.
6Follow-up questions
Which record would you keep if duplicates differ in quality?
That is a business rule, not a collection question. If later records are more complete, the merge function can choose, for example (a, b) -> b.updatedAt().isAfter(a.updatedAt()) ? b : a, while the LinkedHashMap still keeps the position of the first occurrence. We should make the rule explicit and test it.
How much memory does the seen set need?
Roughly a HashMap node, a String and its byte array per email, so around 80 to 100 bytes each for a typical address, or several hundred megabytes for 5 million. If that is too much, we can store a 64-bit hash of the normalised email instead and accept a negligible collision risk, or sort by email with positions and dedupe without a set.
7Conclusion
In this answer, we saw that distinct() keeps the first occurrence in order on a sequential stream, but compares whole objects, so it cannot deduplicate by email. A loop with a seen set of normalised emails, or toMap with a keep-first merge function and LinkedHashMap::new, keeps the first record per email in original order. Parallel ordered deduplication is expensive, and unordered() only helps if order does not matter. Pre-sizing with the Java 19 factories avoids resizes, and emails must be normalised for case and whitespace before comparison.
Open with
First, stream distinct is not enough here. On a sequential ordered stream it does keep the first occurrence in encounter order, using a set of seen elements, but it compares whole records with equals, so two records with the same email and different ids both survive.
Then, if they want more
Collecting the records into a LinkedHashSet has the same problem. To dedupe by email, I would do a single loop with a seen set of normalised emails: if seen.add returns true, I append the record to the output list. That keeps the first occurrence and the original order.
The stream version is toMap with the email as key, the record as value, a merge function that keeps the first, and LinkedHashMap::new as the supplier, then take the values. I would pre-size the collections, for example HashSet.newHashSet or LinkedHashSet.newLinkedHashSet with five million on Java 19 and later, to avoid around nineteen resizes.
I would normalise emails with strip and toLowerCase with Locale.ROOT before comparing.
For parallel, keeping encounter order makes distinct and the ordered collectors expensive, because partial results must be merged in order. unordered helps only if I do not care which occurrence or what order I keep, which here I do, so I would stay sequential; five million records is a fast single pass anyway.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 19
- 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 "You must deduplicate a list of 5 million customer records by email while keeping the...": https://scrivio-interview-library.netlify.app/java/sets/8b3fd75756/