Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two ArrayLists without duplicates? [duplicate]

Tags:

java

arraylist

I have two arrayLists

ArrayList one = {A, B, C, D, E} ArrayList two = {B, D, F, G}   

I want to have my final ArrayList which will have All the elements of one and the elements which are only in two and not in one.

So ArrayList final = {A, B, C, D, E, F, G}.

How can I do this?

like image 547
Navaneeth Sen Avatar asked May 13 '13 10:05

Navaneeth Sen


People also ask

How do I merge two sorted ArrayLists?

Step 1 : Let arrayA and arrayB be two sorted integer input arrays. Step 2 : Declare mergedArray with combined size of arrayA and arrayB . Step 4 : Smaller element in arrayA[i] and arrayB[j] is assigned to mergedArray[k] .

Can ArrayLists have duplicates?

ArrayList allows duplicate values while HashSet doesn't allow duplicates values. Ordering : ArrayList maintains the order of the object in which they are inserted while HashSet is an unordered collection and doesn't maintain any order.

Does ArrayList remove duplicates?

Duplicate items can be removed from the ArrayList by using a HashSet as duplicate items are not allowed in a HashSet. So the ArrayList is converted into a HashSet and that removes the duplicate items. Then the HashSet is converted back into an ArrayList.


Video Answer


2 Answers

Either:

Set<Foo> fooSet = new LinkedHashSet<>(one); fooSet.addAll(two); List<Foo> finalFoo = new ArrayList<>(fooSet); 

or

List<Foo> twoCopy = new ArrayList<>(two); twoCopy.removeAll(one); one.addAll(twoCopy); 
like image 109
Puce Avatar answered Sep 23 '22 21:09

Puce


for (Object x : two){    if (!one.contains(x))       one.add(x); } 

assuming you don't want to use the set suggested in the comment. If you are looking for something fancier than this please clarify your question.

like image 31
John B Avatar answered Sep 21 '22 21:09

John B