How to find the intersection of two arrays in java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 09-Jan-2018 14:55:22
Advertisements