Learnitweb

Java program to find the common elements between two arrays

You can find common elements between two arrays using Java 8 Streams by filtering elements present in both arrays. Below are two approaches:

Approach 1: Using filter() and contains() (For Small Arrays)

This approach works well when the second array is small since contains() runs in O(n) time.

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

public class CommonElements {
    public static void main(String[] args) {
        Integer[] array1 = {1, 2, 3, 4, 5, 6};
        Integer[] array2 = {4, 5, 6, 7, 8};

        List<Integer> commonElements = Arrays.stream(array1)
                .filter(Arrays.asList(array2)::contains) // Keep elements found in array2
                .collect(Collectors.toList());

        System.out.println("Common Elements: " + commonElements);
    }
}

Output:

Common Elements: [4, 5, 6]

Approach 2: Using Set for Better Performance (O(n) Complexity)

If the second array is large, using a HashSet improves efficiency.

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

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

        Set<Integer> set = Arrays.stream(array2).boxed().collect(Collectors.toSet()); // Convert array2 to Set

        List<Integer> commonElements = Arrays.stream(array1)
                .filter(set::contains) // Check presence in Set (O(1) lookup)
                .boxed()
                .collect(Collectors.toList());

        System.out.println("Common Elements: " + commonElements);
    }
}

Output:

Common Elements: [4, 5, 6]