How can we find the intersection of multiple arrays in Java?
You can use HashSet to find the intersection of multiple arrays. The specific steps are as follows:
- Convert the first array into a HashSet.
- Traverse through the other arrays and add their elements to the HashSet of the first array.
- In the end, the HashSet is simply the intersection of all the arrays.
Here is a sample code:
import java.util.*;
public class ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {3, 4, 5, 6, 7};
int[] arr3 = {5, 6, 7, 8, 9};
Set<Integer> set = new HashSet<>();
for (int num : arr1) {
set.add(num);
}
for (int i = 1; i < 3; i++) {
Set<Integer> tempSet = new HashSet<>();
for (int num : set) {
if (contains(arr2, num) && contains(arr3, num)) {
tempSet.add(num);
}
}
set = tempSet;
}
System.out.println("Intersection of arrays: " + set);
}
public static boolean contains(int[] arr, int num) {
for (int i : arr) {
if (i == num) {
return true;
}
}
return false;
}
}
Please note that the code uses a contains method to determine if an element is present in an array, making it easy to check if the element is present in all arrays.