package JavaPrograms;
import java.util.HashSet;
import java.util.Set;
public class IntersectionofArrays {
public static void main(String[] args) {
int[] firstInts = new int[]{2,3,4,5,5,7,9,0,0,0};
int[] secondInts = new int[]{2,44,2,33,8,5,12,14,0};
Set intersects = intersectArrays(firstInts, secondInts);
// print out the set of intersecting integers
for (Integer theInt : intersects) {
System.out.println("intersect on " + theInt);
}
}
public static Set intersectArrays(int[] first, int[] second) {
// initialize a return set for intersections
Set intsIntersect = new HashSet();
// load first array to a hash
HashSet array1ToHash = new HashSet();
for (int i = 0; i < first.length; i++) {
array1ToHash.add(first[i]);
}
// check second array for matches within the hash
for (int i = 0; i < second.length; i++) {
if (array1ToHash.contains(second[i])) {
// add to the intersect array
intsIntersect.add(second[i]);
}
}
return intsIntersect;
}
}