Java – Program Intersection of Two Arrays

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<Integer> intersects = intersectArrays(firstInts, secondInts);  

	        // print out the set of intersecting integers  
	        for (Integer theInt : intersects) {  
	            System.out.println("intersect on " + theInt);  
	        }  

	    }  

	    public static Set<Integer> intersectArrays(int[] first, int[] second) {  
	        // initialize a return set for intersections  
	        Set<Integer> intsIntersect = new HashSet<Integer>();  

	        // load first array to a hash  
	        HashSet<Integer> array1ToHash = new HashSet<Integer>();  
	        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;  

	    }  

	}

 

You might also like More from author

Loading...