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?
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] .
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With