如何使用 Guava 检查集合中的每个元素是否彼此相等

How to use Guava to check if every element in a collection are equal to each other

有没有一种简单的方法可以使用 Guava 检查我的 Collection 是否包含相同的元素?

我认为您不需要 Guava。您可以简单地将 Collection 中的所有对象传递到 Set 中,如果您得到大小为 1Set,那么 Collection 中的所有对象] 将被视为相等(因为根据定义,Set 不能包含重复项)。例如:

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

更好的是,正如@blgt 所建议的那样,HashSet class has a constructor 带有 Collection 参数,因此您可以这样做:

public boolean checkCollectionForEqualObjects(Collection<SomeObject> collection) {
    return new HashSet<>(collection).size() == 1;
}