Is there a simple way to use Guava
to check if my Collection
contains the same elements?
Asked
Active
Viewed 1,337 times
0

JohnnyGnomez
- 49
- 6
-
Check this answer http://stackoverflow.com/questions/12242083/remove-duplicates-from-list-using-guava – Ugur Artun Feb 05 '15 at 14:09
-
Your 4 best alternatives are listed in this answer: http://stackoverflow.com/a/29288616/276052 – aioobe Apr 06 '17 at 06:31
1 Answers
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
-
`HashSet` has a constructor can take a `Collection` as an argument, so you don't need to do the iteration yourself – blgt Feb 05 '15 at 14:11
-