3

Possible Duplicate:
How to most elegantly iterate through parallel collections?
Is there an accepted Java equivalent to Python's zip()?

I have to iterate simultaneously over two Collections of objects to see if their members are equal. Is there a way of using a counter to access the object or do something similar to the for loop below ?

Boolean compareCollection(Collection<Object> c1, Collection<Object> c2)
{
     //something like -
     for (Object ob1 : c1, Object ob2 : c2){
           //check if ob1.val == ob2.val
     }
     return true;
}
Community
  • 1
  • 1
user379151
  • 1,289
  • 1
  • 16
  • 25

2 Answers2

2

Something like this:

public static boolean compareCollection(Collection<Object> c1, Collection<Object> c2)   {
    if (c1 == null)
        return c2 == null;
    else if (c2 == null || c1.size() != c2.size())
        return false;
    Iterator<Object> it1 = c1.iterator();
    Iterator<Object> it2 = c2.iterator();
    while (it1.hasNext()) {
        Object o1 = it1.next();
        Object o2 = it2.next();
        if (!o1.equals(o2))
            return false;
    }
     return true;
}

Of course, you'll have to parameterize the collections with the right type (which I'm guessing is not just Object) and making the appropriate comparison:

if (!o1.val.equals(o2.val))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
1

Could you just use List.equals(), which implements similar logic?

Also, commons-collections ListUtils.isListEquals may be what you want: http://commons.apache.org/collections/api-release/index.html

wrschneider
  • 17,913
  • 16
  • 96
  • 176