Find Duplicate Elements Using Java Streams
Finding duplicate elements with Java streams means returning the values that occur more than once, not removing them, which is the job of distinct(). The two standard techniques are counting occurrences with Collectors.groupingBy() and counting(), and tracking seen values with a Set whose add() method returns false for repeats.
This page compares both techniques, shows how to find duplicates by a property of objects, how to keep order, and how to report how many times each duplicate occurs.
1. Two Techniques
// 1. Count occurrences, keep counts > 1 (any Java 8+)
Set<String> dups = items.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toCollection(LinkedHashSet::new));
// 2. Set.add() returns false for a value already seen (sequential streams only)
Set<String> seen = new HashSet<>();
Set<String> dups2 = items.stream().filter(x -> !seen.add(x)).collect(Collectors.toSet());
2. How Each Technique Works
The counting technique builds a frequency map in one pass and then filters it; it is correct for sequential and parallel streams and also tells you how often each duplicate occurs. The Set.add() technique relies on a side effect: add() returns false when the value is already present. It is short and fast but uses shared mutable state, so it is only safe on sequential streams.
Both rely on equals() and hashCode(), so they work out of the box for strings, numbers and records.
LinkedHashMap keeps the order of first appearance.3. Real-World Examples
Example 1: Duplicate values with counts (Java 9+)
Find invoice numbers that were submitted more than once, and how many times.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class DuplicateInvoices {
public static void main(String[] args) {
List<String> submitted = List.of("INV-7", "INV-2", "INV-7", "INV-9", "INV-2", "INV-7", "INV-4");
Map<String, Long> duplicates = submitted.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
System.out.println("Duplicates: " + duplicates);
}
}
Duplicates: {INV-7=3, INV-2=2}
How it works: The first collect() counts every invoice in first-seen order; the second stream keeps only counts above one.
Example 2: The Set.add() technique (Java 9+)
Find repeated seat numbers in a booking request, in the order the repeats occur.
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class RepeatedSeats {
public static void main(String[] args) {
List<String> seats = List.of("A1", "B4", "A1", "C2", "B4", "A1");
Set<String> seen = new HashSet<>();
Set<String> repeated = seats.stream()
.filter(seat -> !seen.add(seat)) // add() is false for repeats
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println("Repeated seats: " + repeated);
}
}
Repeated seats: [A1, B4]
How it works: Each repeat fails add() and passes the filter. Collecting into a LinkedHashSet lists each duplicate once. This works only on a sequential stream, because seen is shared mutable state.
Example 3: Duplicate objects by a property (Java 16+)
Find customers registered more than once with the same email address, ignoring case.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class DuplicateEmails {
record Customer(int id, String name, String email) { }
public static void main(String[] args) {
List<Customer> customers = List.of(
new Customer(1, "Asha", "asha@mail.in"), new Customer(2, "Ravi", "ravi@mail.in"),
new Customer(3, "Asha R", "ASHA@mail.in"), new Customer(4, "Meera", "meera@mail.in"),
new Customer(5, "Ravi K", "ravi@mail.in"));
Map<String, List<Integer>> duplicateIds = customers.stream()
.collect(Collectors.groupingBy(c -> c.email().toLowerCase(), TreeMap::new,
Collectors.mapping(Customer::id, Collectors.toList())))
.entrySet().stream()
.filter(e -> e.getValue().size() > 1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, TreeMap::new));
System.out.println(duplicateIds);
}
}
{asha@mail.in=[1, 3], ravi@mail.in=[2, 5]}
How it works: Grouping by the normalised email collects the ids of all customers with that email. Groups with more than one id are the duplicates, and the ids tell you exactly which records to merge.
Example 4: Duplicates in a primitive array
Find duplicated sensor ids in an int[], sorted.
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class DuplicateSensorIds {
public static void main(String[] args) {
int[] ids = {104, 221, 104, 309, 221, 410, 104};
int[] duplicates = IntStream.of(ids)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.mapToInt(Map.Entry::getKey)
.sorted()
.toArray();
System.out.println(java.util.Arrays.toString(duplicates));
}
}
[104, 221]
How it works: boxed() is needed because collectors work with objects. After filtering, mapToInt() returns to primitive values for sorting and the array result.
4. Real-World Use Cases
- Data quality: duplicate customer emails, phone numbers or tax ids before an import.
- Payments: invoice or transaction ids submitted twice.
- Bookings: seats or rooms assigned more than once.
- Configuration checks: repeated keys in lists of settings.
5. Important Points
- Equality: duplicates are decided by
equals()andhashCode(); normalise values (case, spaces) first if needed. - Order: use
LinkedHashMap/LinkedHashSetto report duplicates in first-seen order. - Set.add() technique: sequential streams only.
- Nulls:
groupingBy()rejects null keys; filter them first. - Memory: both techniques store every distinct value.
6. Techniques Compared
| Technique | Gives counts | Parallel-safe | Notes |
|---|---|---|---|
groupingBy(identity(), counting()) + filter | Yes | Yes | Most versatile |
filter(x -> !seen.add(x)) | No | No | Short; side effect |
Collections.frequency(list, x) > 1 per element | Yes | Yes | O(n2); only for tiny lists |
distinct() | - | Yes | Removes duplicates; does not find them |
To remove duplicates instead, see distinct(); to count every element, see Element Frequency.
7. Common Mistakes and Best Practices
Using Collections.frequency() inside the stream
list.stream().filter(x -> Collections.frequency(list, x) > 1).distinct().toList(); // scans the list for every element
It is quadratic: each element triggers a full scan. Count once with groupingBy().
Using the Set technique in parallel
Set<String> seen = new HashSet<>();
list.parallelStream().filter(x -> !seen.add(x)).toList(); // HashSet is not thread-safe
Other mistakes to avoid
- Confusing
distinct()with finding duplicates. - Forgetting to normalise case or whitespace before comparing.
- Using objects without
equals()/hashCode(), which compare by identity.
8. Summary
- Count with
groupingBy(identity(), counting())and keep counts above one. filter(x -> !seen.add(x))is short but sequential-only.- Group by a normalised field to find duplicate objects.
- Use linked collections to report duplicates in first-seen order.
9. References
Frequently Asked Questions (FAQ)
Q1. How do I find duplicate elements in a list with Java 8 streams?
Count occurrences with groupingBy(Function.identity(), counting()), then stream the entries and keep those with a count greater than 1.
Q2. What is the fastest simple way to find duplicates?
On a sequential stream, filter(x -> !seen.add(x)) with a HashSet is short and fast, but it uses shared mutable state and is not safe in parallel.
Q3. How do I find duplicate objects by a field?
Group by the field, for example groupingBy(Customer::email), and keep the groups whose list has more than one element.
Q4. How do I keep duplicates in the order they first appear?
Use LinkedHashMap::new as the map factory in groupingBy() and collect the result keys into a LinkedHashSet.
Q5. Does distinct() find duplicates?
No. distinct() removes repeated elements and keeps one of each. To find which values repeat, count them.