In this post we will learn how to find out the common elements between two arrays. We will be using the below approaches.
- Normal Iterative method
- Using retainAll() method of ArrayList class
- Using containsKey() method of HashMap
Lets take a look at it one by one
1. Normal Iterative method
In this method we will be iterating both array (array1, array2) and will be comparing each element of one array with the other array, if common element is found then we will adding it to our commonList.
import java.util.ArrayList; import java.util.List; public class CommonElementsInArrays { public static void main(String args[]) { Integer[] array1 = {1, 2, 3, 4, 5, 4, 7, 9}; Integer[] array2 = {3, 4, 5, 6, 7, 10, 40, 2}; List<Integer> commonList = new ArrayList<Integer>(); for(int i=0;i<array1.length;i++) { for(int j=0;j<array2.length;j++) { if(array2[j]==array1[i]) { commonList.add(array2[j]); } } } System.out.println("Common Elements : "+commonList); } }
Output :
Common Elements : [2, 3, 4, 5, 4, 7]
2. Using retainAll() method of ArrayList class
This method is the easiest of all to find the common elements between two arrays. In this method, we will create two ArrayList by converting both arrays to a list using Arrays.asList() method and then use retainAll() method of ArrayList to retain only common elements between the two lists.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CommonElementsInArrays { public static void main(String args[]) { Integer[] array1 = {1, 2, 3, 4, 5, 7, 9}; Integer[] array2 = {3, 4, 5, 6, 7, 10, 40, 2}; List<Integer> list1 = new ArrayList(Arrays.asList(array1)); List<Integer> list2 = new ArrayList(Arrays.asList(array2)); list1.retainAll(list2); System.out.println("Common Elements : "+list1); } }
Output :
Common Elements : [2, 3, 4, 5, 7]
3. Using containsKey() method of HashMap
In this method we will be creating two HashMaps and will add the elements of the array1 to the map1 using put() method and we will be using containsKey() method to compare and add only the common element to the commonElementsMap.
import java.util.HashMap; import java.util.Map; public class CommonElementsInArrays { public static void main(String args[]) { Integer[] array1 = {1, 2, 3, 4, 5, 7, 9}; Integer[] array2 = {3, 4, 5, 6, 7, 10, 40, 2}; Map map1 = new HashMap(); Map commonElementsMap = new HashMap(); for(int i = 0; i < array1.length; i++) { map1.put(array1[i], "val"+i); } for(int i = 0; i < array2.length; i++) { if(!map1.containsKey(array2[i])) map1.put(array1[i], i); else commonElementsMap.put(array2[i], "val"+i); } System.out.println("Common Elements : " + commonElementsMap.keySet()); } }
Output :
Common Elements : [2, 3, 4, 5, 7]
Leave a Reply