I need to provide a Java solution that given two list, a & b, that returns a value that is present in one list but not in another.
e.g.
lists a = [26, 13, 88, 9]
lists b = [26, 1, 8, 12]
I need to provide a Java solution that given two list, a & b, that returns a value that is present in one list but not in another.
e.g.
lists a = [26, 13, 88, 9]
lists b = [26, 1, 8, 12]
for those kind of operation it would be better to use collections, the method removeAll() will filter the data containers, from the doc:
Removes from this list all of its elements that are contained in the specified collection (optional operation).
List<Integer> myVarListA = Arrays.asList(26, 13, 88, 9);
List<Integer> myVarListB = Arrays.asList(26, 1, 8, 12);
List<Integer> myVarListAcomplementB = new ArrayList<>(myVarListA);
List<Integer> myVarListBcomplementA = new ArrayList<>(myVarListB);
myVarListAcomplementB.removeAll(myVarListB);
myVarListBcomplementA.removeAll(myVarListA);
System.out.println("elements in A but no in B: " + myVarListAcomplementB);
System.out.println("elements in B but no in A: " + myVarListBcomplementA);
myVarListBcomplementA.addAll(myVarListAcomplementB);
System.out.println("both together: " + myVarListBcomplementA);
Simple solution is to calculate the intersection and remove that from the desired list. If you only want what is missing, you can optimize this a little by going a solution like ΦXocę 웃 Пepeúpa ツ.
The great thing about this solution is that you can easily expand this to use 3+ sets/lists. Instead of A-B = diff or A-I(A,B)=diff, you can also do A-I(A,I(B,C)) to find what A is missing from the common set between A, B and C.
public static <T> HashSet<T> intersection(Collection<T> a, Collection<T> b) {
HashSet<T> aMinusB = new HashSet<>(a);
aMinusB.removeAll(b);
HashSet<T> common = new HashSet<>(a);
common.removeAll(aMinusB);
return common;
}
Let's call the intersection set Collection I = intersection(a,b);
.
Now if you want to find what is missing from list A that was in B:
new LinkedList(A).removeAll(I);//ordered and possibly containing duplicates
OR
new ArrayList(A).removeAll(I);//ordered and possibly containing duplicates. Faster copy time, but slower to remove elements. Experiment with this and LinkedList for speed.
OR
new LinkedHashSet<T>(a).removeAll(I);//ordered and unique
OR
new HashSet<T>(a).removeAll(I);//unique and no order
Also, this question is effectively duplicate of How to do union, intersect, difference and reverse data in java
Simply parse the second list and add unique elements to the first, delete others.
for (Integer elem : secondList)
if (firstList.contains(elem))
firstList.remove(elem);
else
firstList.add(elem);
In firstList
you will have the values present only in one of the lists.