
How to Find Common Elements of Two UnSorted Array? Below is a simple Java Code which shows it.
Steps:
- Find 1st small array.
- Iterate through small array and find elements in largest array.
- In case of match, add it to separate new array.
- Display final array.
Approach-1:
package com.crunchify; import java.util.HashSet; /** * @author Crunchify.com */ public class CrunchifyIntersection { public static void main(String[] args) { Integer[ ] arrayOne = { 1, 4, 5, 2, 7, 3, 9 }; Integer[ ] arrayTwo = { 5, 2, 4, 9, 5 }; Integer[ ] common = CrunchifyIntersection.findCommon( arrayOne, arrayTwo ); System.out.print( "Common Elements Between Two Arrays: " ); for( Integer entry : common ) { System.out.print( entry + " " ); } } public static Integer[ ] findCommon( Integer[ ] arrayOne, Integer[ ] arrayTwo ) { Integer[ ] arrayToHash; Integer[ ] arrayToSearch; if( arrayOne.length < arrayTwo.length ) { arrayToHash = arrayOne; arrayToSearch = arrayTwo; } else { arrayToHash = arrayTwo; arrayToSearch = arrayOne; } HashSet<Integer> intersection = new HashSet<Integer>( ); HashSet<Integer> hashedArray = new HashSet<Integer>( ); for( Integer entry : arrayToHash ) { hashedArray.add( entry ); } for( Integer entry : arrayToSearch ) { if( hashedArray.contains( entry ) ) { intersection.add( entry ); } } return intersection.toArray( new Integer[ 0 ] ); } }
Output:
Common Elements Between Two Arrays: 2 4 5 9
Approach-2
Below approach is suggested by our reader Maksudur rahman
as you see it in below comment section. Please find here complete example.
package crunchify.com.tutorials; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; /** * @author Crunchify.com * */ public class CrunchifyIntersection { public static void main(String[] args) { Integer[] arrayOne = { 1, 4, 5, 2, 7, 3, 9 }; Integer[] arrayTwo = { 5, 2, 4, 9, 5 }; Set<Integer> crunchifySet1 = new LinkedHashSet<Integer>(Arrays.asList(arrayOne)); Set<Integer> crunchifySet2 = new LinkedHashSet<Integer>(Arrays.asList(arrayTwo)); for (Integer crunchify : crunchifySet2) { if (!crunchifySet1.add(crunchify)) { System.out.println("The duplicate element of an Array is " + crunchify); } } } }
Output:
The duplicate element of an Array is 5 The duplicate element of an Array is 2 The duplicate element of an Array is 4 The duplicate element of an Array is 9