Comparing two collections in Java

I have two collections in a Java class. The first collection contains previous data, the second contains updated data from the previous collection.

I would like to compare the two collections, but I'm not sure if this is an effective way to implement. Collections will contain the same number of items.

Based on the fact that carType is the same in every collection, I want to execute the carType method.

Any help is appreciated.

+8
source share
5 answers

It’s hard to help because you didn’t tell us how you like to compare (peer) collections. Some ideas, hoping one fits:

Compare both collections if they contain the same objects in the same order

Iterator targetIt = target.iterator();
for (Object obj:source)
  if (!obj.equals(targetIt.next()))
    // compare result -> false

,

for (Object obj:source)
  if (target.contains(obj))
    // compare result -> false

,

Iterator targetIt = target.iterator();
for (Object obj:source)
  if (!obj.equals(targetIt.next())
    // Element has changed

, . , . , . equals() Car!

public List<Car> findUpdatedCars(Collection<Car> oldCars, Collection<Car> newCars)
  List<Car> updatedCars = new ArrayList<Car>();
  Iterator oldIt = oldCars.iterator();
  for (Car newCar:newCars) {
    if (!newCar.equals(oldIt.next()) {
      updatedCars.add(newCar);
    }
  }
  return updatedCars;
}
+22

A B , A B B A. , Java, A B,

boolean collectionsAreEqual = A.containsAll(B) && B.containsAll(A);
+8
  • Map<Entity, Integer>, Entity - , , Integer - , .
  • , Map. , Integer , . Integer , (Entity, Integer) .

, , hashCode().

+6

Slightly updated considering zero values:

static <T> boolean equals(Collection<T> lhs, Collection<T> rhs) {
    boolean equals = false;
    if(lhs!=null && rhs!=null) {
       equals = lhs.size( ) == rhs.size( ) && lhs.containsAll(rhs)  && rhs.containsAll(lhs);
    } else if (lhs==null && rhs==null) {
       equals = true;
    }
 return equals;
}
+4
source

If you do not worry about cases such as (2,2,3), (2,3,3):

static <T> boolean equals(Collection<T> lhs, Collection<T> rhs) {
    return lhs.size( ) == rhs.size( ) && lhs.containsAll(rhs)  && rhs.containsAll(lhs);
}
+1
source

All Articles