How to get intersection between two arrays

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.