Java Program to Find the Intersection of Two Arrays of Integers

In the previous article, we have seen Java Program to Find the Intersection of Two Arrays of String

In this article we are going to see how to find intersection of two integer arrays using Java programming language.

Java Program to Find the Intersection of Two Arrays of Integers

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways to find the intersection of two arrays of integers.

Method-1: Java Program to Find the Intersection of Two Arrays of Integers By Sorting both arrays

Approach:

  • Sort the two arrays.
  • Declare a set and initialize two pointers, i = 0, j = 0.
  • if the current element of the first array is equal to the current element of the second array do add the element to the set and increment both pointers by one.
  • If the current element of the first array is less than the current element of the second array do i++.
  • if the current element of the first array is greater than the current element of the second array do j++.
  • Return the set.

Program:

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;

public class Main
  {
    public static void main(String[] args) {
        // initialize the arrays
        int[] nums1 = { 1, 2, 5, 9, 7, 10 };
        int[] nums2 = { 7, 2, 7, 5 };
        // calling the method and printing the result
        System.out.println("The intersection of " + Arrays.toString(nums1) + " and " + Arrays.toString(nums2) + " is "
                + intersection(nums1, nums2));
    }

    static Set<Integer> intersection(int[] nums1, int[] nums2) {
        // sorting both arrays
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        // initializing two pointers
        int i = 0, j = 0;
        // declaring a set
        Set<Integer> set = new HashSet<>();
        while (i < nums1.length && j < nums2.length) {
            // if the current element of the first array is equal to the
            // current element of the second array add element to the set
            if (nums1[i] == nums2[j]) {
                set.add(nums1[i]);
                i++;
                j++;
                // if the current element of the first array
                // is less than the current element of the second array
            } else if (nums1[i] < nums2[j]) {
                i++;
            // if the current element of the first array
            // is greater than the current element of the second array
            } else {
                j++;
            }
        }
        return set;
    }
}

Output:

The intersection of [1, 2, 5, 9, 7, 10] and [7, 2, 7, 5] is [2, 5, 7]

Method-2: Java Program to Find the Intersection of Two Arrays of Integers By Sorting One Array and Applying Binary Search

Approach:

  • Sort the smaller array (for better performance).
  • Declare a set.
  • Iterate through the unsorted array and binary search for each element in the sorted array.
  • If the element if found put it in the set.
  • Return the set.

Program:

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;

public class Main 
{
    public static void main(String[] args) 
    {
        // initialize the arrays
        int[] nums1 = { 1, 2, 5, 9, 7, 10 };
        int[] nums2 = { 7, 2, 7, 5 };
        // calling the method and printing the result
        System.out.println("The intersection of " + Arrays.toString(nums1) + " and " + Arrays.toString(nums2) + " is "
                + intersection_binarySearch(nums1, nums2));
    }

    static Set<Integer> intersection_binarySearch(int[] nums1, int[] nums2) {
        // initializing a set
        Set<Integer> set = new HashSet<>();

        // sorting the smaller array for better performance
        if (nums1.length < nums2.length) 
        {
            Arrays.sort(nums1);
        } 
        else 
        {
         // making nums1 smaller of the two arrays for easier operations
            int[] temp = nums1;
            nums1 = nums2;
            nums2 = temp;
            Arrays.sort(nums1);
        }

        // iterating through the first array
        for (int i: nums2) {
            // calling the binary search method
            if (Arrays.binarySearch(nums1, i) >= 0) 
            {
                // adding the element to the set
                set.add(i);
            }
        }
        return set;
    }

}

Output:

The intersection of [1, 2, 5, 9, 7, 10] and [7, 2, 7, 5] is [2, 5, 7]

Method-3: Java Program to Find the Intersection of Two Arrays of Integers By Using two HashSets and Scanner Class

Approach:

  • Create scanner class object.
  • Ask use length of the 1st
  • Initialize the 1st array with given size.
  • Ask the user for 1st array elements.
  • Ask use length of the 2nd
  • Initialize the 2nd array with given size.
  • Ask the user for 2nd array elements.
  • Initialize two sets.
  • Add the elements of the 1st array into the 1st
  • Iterate through the second set and if the current is present in the first set then add it in the second set.
  • Return the second set.

Program:

import java.util.Arrays;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) 
    {
        // initialize the arrays
        // create scanner class object
        Scanner sc = new Scanner(System.in);
        // take input from user for array size
        System.out.print("Enter the size of 1st array: ");
        int n = sc.nextInt();
        // initialize array with size n
        int[] nums1 = new int[n];
        // take input from user for array elements
        System.out.print("Enter elements of the 1st array: ");
        for (int i = 0; i < n; i++) 
        {
            nums1[i] = sc.nextInt();
        }
        System.out.print("Enter the size of 2nd array: ");
        int m = sc.nextInt();
        // initialize array with size n
        int[] nums2 = new int[m];
        // take input from user for array elements
        System.out.print("Enter elements of the 2nd array: ");
        for (int i = 0; i < m; i++) 
        {
            nums2[i] = sc.nextInt();
        }
        // calling the method and printing the result
        System.out.println("The intersection of " + Arrays.toString(nums1) + " and " + Arrays.toString(nums2) + " is "
                + intersectionHashSet(nums1, nums2));
    }

    static Set<Integer> intersectionHashSet(int[] nums1, int[] nums2) 
    {
        // initializing two sets
        Set<Integer> set = new HashSet<>();
        Set<Integer> intersect = new HashSet<>();
        // addd the elements of the first array to the set
        for (int i = 0; i < nums1.length; i++) 
        {
            set.add(nums1[i]);
        }
        // add the common elements to the second set
        for (int i = 0; i < nums2.length; i++) 
        {
            if (set.contains(nums2[i])) {
                intersect.add(nums2[i]);
            }
        }
        return intersect;
    }

}


Output:

Enter the size of 1st array: 4
Enter elements of the 1st array: 1 2 3 4
Enter the size of 2nd array: 5
Enter elements of the 2nd array: 2 3 4 5 6
The intersection of [1, 2, 3, 4] and [2, 3, 4, 5, 6] is [2, 3, 4]

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: