In this post on How to find common elements between two Arrays. we will understand how to find common elements between two given Arrays. It is a very common interview question where it is asked with a condition not to use any inbuilt classes or methods or any inbuilt data structure like List or Set.
A very easy approach to find common elements between two input arrays is to loop through one of the arrays in the outer loop and then traverse through the other array in the inner loop and compare the elements of the outer array elements with all the elements of the inner array. If we get the same element then print it and break it from the inner loop. that’s yet.
You may also like –
Get largest and smallest number in the given Array
Find duplicate elements in an Array
Java program with array of Integers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.kkjavatutorials.client; public class FindCommonElementsFromArrays1 { public static void main(String[] args) { int[] inputArray1 = { 20, 30, 32,100,199,201,500 }; int[] inputArray2 = {600,500,30,201,299,900,901 }; //Here Intillay looping through the first input array(inputArray1)in the outer loop for (int i = 0; i < inputArray1.length; i++) { /* We traverse through the second input array(inputArray2) in the inner loop and comparing the elements of the outer array(inputArray1) with all the elements of the inner loop array*/ for (int j = 0; j < inputArray2.length; j++) { if (inputArray1[i] == inputArray2[j]) { System.out.println(inputArray1[i]); break; } } } } } |
Output:
1 2 3 |
30 201 500 |
Java program with array of Strings
Here is the logic to find common elements between two arrays is very similar in the case of an array of Strings. Only thing that differs is how you compare Strings you will have to use the .equals method of String class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.kkjavatutorials.client; public class FindCommonElementsFromArrays2 { public static void main(String[] args) { String[] inputArray1 = { "Mumbai", "Chennai","New York", "California" }; String[] inputArray2 = { "California", "Mumbai", "Alaska", "Arizona", "Delaware", "New York" }; //Here Intillay looping through the first input array(inputArray1)in the outer loop for (int i = 0; i < inputArray1.length; i++) { /* We traverse through the second input array(inputArray2) in an inner loop and compare the elements of the outer array(inputArray1) with all the elements of the inner loop array*/ for (int j = 0; j < inputArray2.length; j++) { if (inputArray1[i].equals(inputArray2[j])) { System.out.println(inputArray1[i]); break; } } } } } |
Output:
1 2 3 |
Mumbai New York California |
That’s all about this topic Java Program to find duplicate elements in an Array. If you have any doubts or any suggestions to make please drop a comment.