Reputation: 227
I have two lists. For example:
A = {21, 41, 96, 02}
B = {21, 96, 32, 952, 1835}
What I want is this as a result: R = {32, 952, 1835}
Like this:
After this I want to add the result R
to A
:
A = {21, 41, 96, 02, 32, 952, 1835}
Upvotes: 3
Views: 2700
Reputation: 820
Try this :
import org.apache.commons.collections.CollectionUtils;
[...]
// Returns a Collection containing the exclusive disjunction (symmetric difference) of the given Collections.
Collection disJointList = CollectionUtils.disjunction(a, b);
//To check
for (Object object : disJointList) {
System.out.println(disJointList);
//output is {32, 952, 1835}
}
a.addAll( disJointList );
Upvotes: 0
Reputation: 68640
So, you want the set reunion of those two collections. That's what sets are for.
HashSet<Integer> set = new HashSet<Integer>();
set.addAll(a);
set.addAll(b);
Upvotes: 1
Reputation: 14149
It's simple :)
List<Integer> a = new ArrayList<>(Arrays.asList(21, 41, 96, 02));
List<Integer> b = new ArrayList<>(Arrays.asList(21, 96, 32, 952, 1835));
b.removeAll(a)
// now list b contains (32, 952, 1835)
a.addAll(b);
// now list a contains (21, 41, 96, 02, 32, 952, 1835)
Upvotes: 3
Reputation: 889
So you want to make A = A U B. To do this, you can search for each element of B in A and add the element to A if the search fails. However, making too much search on a list is not recommended.
I would recommend using a HashMap. Create a HashMap and loop through A and B putting anything you see into the map. After that, you can convert map back to a list.
[If you want the order to be the same as in the example, you should convert A to a map. Then you should go through B and for each failed map.get(element) you should be adding that element of B to A.]
Upvotes: 0