Friday, July 19, 2019

How to Find Common Elements Between Two Arrays - Java Program

This post is about writing a Java program to find common elements between two given arrays. It is a common interview question where it is asked with a condition not to use any inbuilt method or any inbuilt data structure like list or set.

Steps for solution

A simple solution to find common elements between two arrays in Java is to loop through one of the array in the outer loop and then traverse through the other array in an inner loop and compare the element of the outer array with all the elements of the inner array.

If similar element is found print it and break from the inner loop.

Find common elements between two given arrays of integers

 
public class FindCommonElement {
 public static void main(String[] args) {
  int[] numArray1 = {1, 4, 5};
  int[] numArray2 = {6, 1, 8, 34, 5};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i] == numArray2[j]){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }  
 }
}

Output

 
1
5

Find common elements between two arrays of strings

Logic to find common elements between two arrays remains same in case of array of Strings. Only thing that changes is how you compare, with Strings you will have to use .equals method.

 
public class FindCommonElement {
 public static void main(String[] args) {
  String[] numArray1 = {"Java", "Scala", "Python"};
  String[] numArray2 = {".Net", "Scala", "Clojure", "Java", 
    "Java Script", "Python"};
  // Outer loop
  for(int i = 0; i < numArray1.length; i++){
   for(int j = 0; j < numArray2.length; j++){// inner loop
    if(numArray1[i].equals(numArray2[j])){
     System.out.println(numArray1[i]);
     break;
    }
   }
  }
 }
}

Output

 
Java
Scala
Python

That's all for this topic How to Find Common Elements Between Two Arrays - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to remove duplicate elements from an array - Java Program
  2. How to remove elements from an array - Java Program
  3. Array in Java
  4. Matrix Addition - Java Program
  5. If Given String Sub-Sequence of Another String - Java Program

You may also like-

  1. Converting string to bytearray - Java Program
  2. Count Total Number of Times Each Character Appears in a String - Java Program
  3. Lambda Expression Comparator example
  4. How to Create Your Own BlockingQueue - Java Program
  5. AtomicInteger in Java Concurrency
  6. New Date and Time API in Java 8
  7. How HashMap internally works in Java
  8. What is Dependency Injection in Spring