How to find the intersection of two arrays in java?


To find the intersection of two arrays in java use two loops. The outer loop is to iterate the elements of the first array whereas, the second loop is to iterate the elements of the second array. Within the second loop compare the elements of the two arrays:

Example

Live Demo

public class IntersectionOfTwoArrays {
   public static void main(String args[]) {
      int myArray1[] = {23, 36, 96, 78, 55};
      int myArray2[] = {78, 45, 19, 73, 55};
      System.out.println("Intersection of the two arrays ::");
     
      for(int i = 0; i<myArray1.length; i++ ) {
         for(int j = 0; j<myArray2.length; j++) {
            if(myArray1[i]==myArray2[j]) {
               System.out.println(myArray2[j]);
            }
         }
      }
   }
}

Output

Intersection of the two arrays ::
78
55

Updated on: 16-Jun-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements