Java: comparing two lists
I have two lists. For example:
A = {21, 41, 96, 02}
B = {21, 96, 32, 952, 1835}
As a result, I want: R = {32, 952, 1835}
Like this:
After that, 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 to set up a reunion of these two collections. What sets is 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 every element of B in and add an element to A if the search fails. However, too many searches in the list are not recommended.
I would recommend using HashMap. Create a HashMap and loop through A and B, placing everything you see on the map. After that, you can convert the card back to a list.
[If you want the order to be the same as in the example, you must convert A to card. Then you have to go through B and for every failed map.get (element) file you have to add that element from B to A.]
Try the following:
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 );