Intersection of Two Arrays in Java

Learn to find the intersection between two arrays in Java using HashSet class. An intersection is a group of common items that belong to two different sets.

Intersection
Intersection

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

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

1. Intersection between two integer arrays

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

import java.util.Arrays;
import java.util.HashSet;

public class Main 
{
  public static void main(String[] args) 
  {
    Integer[] firstArray = {0,1,2,3,4,5,6,7,8,9};
    Integer[] secondArray = {1,3,5,7,9};
    
    HashSet<Integer> set = new HashSet<>(); 
    
    set.addAll(Arrays.asList(firstArray));
    
    set.retainAll(Arrays.asList(secondArray));
    
    System.out.println(set);
    
    //convert to array
    Integer[] intersection = {};
    intersection = set.toArray(intersection);
    
    System.out.println(Arrays.toString(intersection));
  }
}

Program output.

[1, 3, 5, 7, 9]
[1, 3, 5, 7, 9]

2. Intersection between two string arrays

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

import java.util.Arrays;
import java.util.HashSet;

public class Main 
{
  public static void main(String[] args) 
  {
    String[] firstArray = {"A", "B", "C", "D"};
    String[] secondArray = {"D", "A", "E", "F"};
    
    HashSet<String> set = new HashSet<>(); 
    
    set.addAll(Arrays.asList(firstArray));
    
    set.retainAll(Arrays.asList(secondArray));
    
    System.out.println(set);
    
    //convert to array
    String[] intersection = {};
    intersection = set.toArray(intersection);
    
    System.out.println(Arrays.toString(intersection));
  }
}

Program output.

[A, D]
[A, D]

Happy Learning !!

Leave a Reply

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