Intersection of Two Arrays in Java

Lokesh Gupta

Learn to find the intersection between two arrays in Java using HashSet class. An intersection is a group of common items that are present in both arrays.

For example, in array1 and array2, the intersection will contain the elements {4,5}.

Integer[] array1 = new Integer[]{1, 2, 3, 4, 5};
Integer[] array2 = new Integer[]{4, 5, 6, 7};

//Intersection elements : {4, 5}
Intersection

1. Find Array Intersection using HashSet

To get the intersection of two arrays, follow these steps:

  • Push the first array in a HashSet.
  • Use retainAll() method to retain only elements which are present in the second array.

Java program to get the intersection between two integer arrays and print the output.

Integer[] array1 = new Integer[]{1, 2, 3, 4, 5};
Integer[] array2 = new Integer[]{4, 5, 6, 7};

HashSet<Integer> set = new HashSet<>();
set.addAll(Arrays.asList(array1));
set.retainAll(Arrays.asList(array2));

Assertions.assertEquals(Set.of(4, 5), set);

//convert to array, if needed
Integer[] intersection = set.toArray(new Integer[0]);

Assertions.assertArrayEquals(new Integer[]{4, 5}, intersection);

2. Using Streams

We can use the Stream APIs to iterate over the elements of an array and check its existence in another array. If the element is present in the second array, it is collected to the intersection result.

Using Streams allows us to perform additional actions on the intersection elements in the same stream pipeline, and collect the results in a variety of target types.

Integer[] array1 = new Integer[]{1, 2, 3, 4, 5};
Integer[] array2 = new Integer[]{4, 5, 6, 7};

Integer[] intersection = Arrays.stream(array1)
    .distinct()
    .filter(x -> Arrays.asList(array2).contains(x))
    .toArray(Integer[]::new);

Assertions.assertArrayEquals(new Integer[]{4, 5}, intersection);

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode