Tip: Computing the difference of two collections

Tip: 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.

4 Comments
  • Posted at 2:34 am, October 23, 2009

    And, thank you EMF, where the code for computing the difference originally came from! 🙂

    Boris

  • Posted at 7:22 am, October 23, 2009

    so: thanks EMF 😉

    ekke

  • Matthew Hall
    Posted at 7:35 pm, October 23, 2009

    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));
        }
      });
    
  • Elias Volanakis
    Posted at 12:58 am, October 27, 2009

    Thanks everybody for the comments and snippet.