on Oct 23rd, 2009Tip: Computing the difference of two collections
Sometimes you have two collections and want to know how they differ. It would also be useful to have a series of steps that transform collection ‘A’ into collection ‘B’ (or the reverse).
private static List list1 = Arrays.asList("a", "b", "c"); private static List list2 = Arrays.asList("a", "c", "d"); // Diff of list1 vs list2: // removed 'b' at 1 // added 'd' at 2
With a little help from the class Diffs (found in the org.eclipse.core.databinding.observable bundle / package), it only takes a few lines, as shown in the snippet below. Thank you, Eclipse Databinding!
If you don’t see the snippet click here.
Related posts:

And, thank you EMF, where the code for computing the difference originally came from!
Boris
so: thanks EMF
ekke
You should also check out ListDiff.accept(ListDiffVisitor) which interprets composite changes (i.e. related adds and removes) as moves or replacements.
ListDiff diff = Diffs.computeListDiff(before, after); diff.accept(new ListDiffVisitor() { public void handleAdd(int index, Object element) { System.out.println(String.format("\tadded '%s' at %d", element, index)); } public void handleRemove(int index, Object element) { System.out.println(String.format("\tremoved '%s' at %d", element, index)); } public void handleMove(int oldIndex, int newIndex, Object element) { System.out.println(String.format("\tmoved '%s' from %d to %d", element, oldIndex, newIndex)); } public void handleReplace(int index, Object oldElement, Object newElement) { System.out.println(String.format("\treplaced '%s' with '%s' at %d", oldElement, newElement, index)); } });Thanks everybody for the comments and snippet.