Intersection of two arrays in Java


The intersection of the two arrays results in those elements that are contained in both of them. If an element is only in one of the arrays, it is not available in the intersection. An example of this is given as follows −

Array 1 = 1 2 5 8 9
Array 2 = 2 4 5 9
Intersection = 2 5 9

A program that demonstrates the intersection of two sorted arrays in Java is given as follows.

Example

Live Demo

public class Example {
   public static void main(String args[]) {
      int arr1[] = {2, 4, 6, 8, 9};
      int arr2[] = {1, 3, 4, 5, 6, 8, 9};
      int m = arr1.length;
      int n = arr2.length;
      int i = 0, j = 0;
      System.out.print("Array 1: ");
      for(int k = 0; k < m; k++) {
         System.out.print(arr1[k] + " "); 
      }
      System.out.print("
"); System.out.print("Array 2: "); for(int k = 0; k < n; k++) { System.out.print(arr2[k] + " "); } System.out.print("
"); System.out.print("Intersection of two arrays is: "); while (i < m && j < n) { if (arr1[i] < arr2[j]) i++; else if (arr2[j] < arr1[i]) j++; else { System.out.print(arr2[j++]+" "); i++; } } } }

The output of the above program is as follows.

Output

Array 1: 2 4 6 8 9
Array 2: 1 3 4 5 6 8 9
Intersection of two arrays is: 4 6 8 9

Now let us understand the above program.

First, the values of the two arrays are printed. The code snippet that demonstrates this is given as follows.

System.out.print("Array 1: ");
for(int k = 0; k < m; k++) {
   System.out.print(arr1[k] + " ");
}
System.out.print("
"); System.out.print("Array 2: "); for(int k = 0; k < n; k++) { System.out.print(arr2[k] + " "); }

Then the intersection of the two arrays i.e. their common elements are displayed using a while loop. The code snippet that demonstrates this is given as follows.

System.out.print("Intersection of two arrays is: ");
while (i < m && j < n) {
   if (arr1[i] < arr2[j])
      i++;
   else if (arr2[j] < arr1[i])
      j++;
   else {
      System.out.print(arr2[j++]+" ");
      i++;
   }
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements