Learnitweb

Java program to find duplicate elements in an array

You can extract duplicate elements from an array using Java 8 Streams by grouping elements and filtering those that appear more than once.

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FindDuplicates {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1, 9};

        List<Integer> duplicates = Arrays.stream(numbers)
                .boxed() // Convert int[] to Stream<Integer>
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // Count occurrences
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() > 1) // Keep only duplicates
                .map(Map.Entry::getKey) // Extract duplicate elements
                .collect(Collectors.toList());

        System.out.println("Duplicate Elements: " + duplicates);
    }
}

Output:

Duplicate Elements: [1, 2, 3]

Alternative: Using Set for Better Performance

If the array is large, using a Set avoids additional memory usage:

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class FindDuplicatesWithSet {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 2, 5, 6, 3, 7, 8, 1, 9};

        Set<Integer> unique = new HashSet<>();
        List<Integer> duplicates = Arrays.stream(numbers)
                .filter(n -> !unique.add(n)) // Add returns false if the element is already in the set
                .boxed()
                .distinct() // Remove duplicate duplicates
                .collect(Collectors.toList());

        System.out.println("Duplicate Elements: " + duplicates);
    }
}