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}
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)
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);
So you want to make A = AU 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.]
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.