Eclipse Yoxos Services Downloads Blogs About
Home > Blogs >

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.

Share and Enjoy:

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • Twitter
  • FriendFeed
  • LinkedIn
  • Reddit
  • Slashdot

Related posts:

4 Responses to “Tip: Computing the difference of two collections”

  1. And, thank you EMF, where the code for computing the difference originally came from! :-)

    Boris

  2. ekke says:

    so: thanks EMF ;-)

    ekke

  3. Matthew Hall says:

    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));
        }
      });
    
  4. Elias Volanakis says:

    Thanks everybody for the comments and snippet.

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
© EclipseSource 2008 - 2009