Android_IT
Android_IT

Reputation: 396

Java - Optimized way to find duplicates from two ArrayLists/Array

I have two Arrays/ArrayLists of Integer. I want to know the optmized way to find duplicates from two and store into the third one.

Array1 = {1,2,3,6,9,10,15,4};  
Array2 = {4,8,6,5,12,14,1,2,9};  
Result Array= {1,2,3,6,9,10,15,4,8,5,12,14,9}

Regards, Android IT

Upvotes: 2

Views: 2137

Answers (4)

Óscar López
Óscar López

Reputation: 235994

You mean, a set union?

List<Integer> array1 = Arrays.asList(1,2,3,6,9,10,15,4);
Set<Integer> set1 = new HashSet<Integer>(array1);

List<Integer> array2 = Arrays.asList(4,8,6,5,12,14,1,2,9);
Set<Integer> set2 = new HashSet<Integer>(array2);

set1.addAll(set2);
List<Integer> resultArray = new ArrayList<Integer>(set1);

Now resultArray contains

[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15]

Upvotes: 1

Fahim Parkar
Fahim Parkar

Reputation: 31633

I would prefer to use Set over HashMap as HashMap need key-value & Sets talks about UNIQUENESS. Sets don't allow duplicates...

Upvotes: 2

Jrom
Jrom

Reputation: 851

Add elements of both arrays into a HashMap where the value is the number of times the element occurs. Then output it to an array.

Upvotes: 1

Luis
Luis

Reputation: 1294

The efficient way, sort the arrays (O(n log n)) and iterate through the lowest in both arrays and only select it if is in both (O(n)), otherwise discard.

Upvotes: 0

Related Questions