List difference in java
I have two ArrayList<Integer>
as follows:
original: 12, 16, 17, 19, 101
selected: 16, 19, 107, 108, 109
I want to do difference on these lists such that in the end I have two lists:
Add: 108,109,107
remove: 12, 17, 101
Length of original and selected lists varies and one can be greater/smaller than the other
Solution 1:
As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.
Solution 2:
List<Integer> original = Arrays.asList(12,16,17,19,101);
List<Integer> selected = Arrays.asList(16,19,107,108,109);
ArrayList<Integer> add = new ArrayList<Integer>(selected);
add.removeAll(original);
System.out.println("Add: " + add);
ArrayList<Integer> remove = new ArrayList<Integer>(original);
remove.removeAll(selected);
System.out.println("Remove: " + remove);
Output:
Add: [107, 108, 109]
Remove: [12, 17, 101]
Uses Collection's removeAll method. See javadocs.
Solution 3:
Intersection: original.retainAll(selected)
.
After that original will contain only elements present in both collections. Returns true if anything changed.
WARNING: This method is very slow for large collections
Solution 4:
For intersection and union operations the natural collection type is a Set rather than a List, its also more efficient to use.
Solution 5:
Using Guava library:
List<Integer> listA = Lists.newArrayList(12,16,17,19,101);
List<Integer> listB = Lists.newArrayList(16,19,107,108,109);
Set<Integer> intersection = Sets.intersection(Sets.newHashSet(listA), Sets.newHashSet(listB));
listA.removeAll(intersection);
listB.removeAll(intersection);