00:00

Find Duplicate Elements Using Java Streams

Last updated:

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

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.

Finding duplicates by counting The list contains INV-7, INV-2, INV-7, INV-9, INV-2 and INV-7. groupingBy with counting produces INV-7 three times, INV-2 twice and INV-9 once. Filtering counts greater than one leaves INV-7 and INV-2 as the duplicates. VALUE COUNT DUPLICATE? INV-7 seen 3 times 3 yes INV-2 seen 2 times 2 yes INV-9 seen once 1 no
Figure 1: Count every value, then keep the ones with a count above one. A 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.

DuplicateInvoices.java
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);
    }
}
Output
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.

RepeatedSeats.java
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);
    }
}
Output
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.

DuplicateEmails.java
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);
    }
}
Output
{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.

DuplicateSensorIds.java
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));
    }
}
Output
[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() and hashCode(); normalise values (case, spaces) first if needed.
  • Order: use LinkedHashMap/LinkedHashSet to 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

TechniqueGives countsParallel-safeNotes
groupingBy(identity(), counting()) + filterYesYesMost versatile
filter(x -> !seen.add(x))NoNoShort; side effect
Collections.frequency(list, x) > 1 per elementYesYesO(n2); only for tiny lists
distinct()-YesRemoves 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

Slow
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

Wrong
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