0

Is there a simple way to use Guava to check if my Collection contains the same elements?

1 Answers1

2

I don't think you need Guava for that. You can simply pass all the objects from the Collection into a Set and if you result with a Set of size 1, then all the objects from the Collection will be considered as equal (because, as per definition, a Set cannot contain duplicates). For example:

public boolean checkCollectionForEqualObjects(Collection<SomeObject> collection) {
    Set<SomeObject> set = new HashSet<>();
    for (SomeObject object : collection) {
       set.add(object);
    }
    return set.size() == 1;
}

Even better, as @blgt suggested, the HashSet class has a constructor with a Collection parameter, so you can just do:

public boolean checkCollectionForEqualObjects(Collection<SomeObject> collection) {
    return new HashSet<>(collection).size() == 1;
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147