List difference in java

As an alternative, you could use CollectionUtils from Apache commons library. It has static intersection, union and subtract methods suitable for your case.


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.


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

Tags:

Java