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.

To get the intersection of two arrays, follow these steps:
- Push first array in a HashSet instance.
- 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?
Let us know if you liked the post. That’s the only way we can improve.