我正在寻找一个方法,如果它在标准库中,可能是类似boolean Collections#areAllUnique(Collection)
的方法。我想要一个当集合中没有重复项时返回true的方法。
显然,对于任何(正确实现的(集合,这都将返回true。
把自己写成collection.size() == new HashSet(collection).size()
也很容易。然而,有几个原因我仍然希望将其视为一个单行库方法:
- 更简单:(
- 上述措施并没有达到应有的效率;如果该方法检测到任何重复,则可以避免构建整个第二集合
一个好的实现可能看起来像
public static <T> boolean areAllUnique(Collection<T> collection) {
if (collection instanceof Set) {
return true;
}
HashSet<T> set = new HashSet<>(collection.size());
for (T t : collection) {
if (set.contains(t)) {
return false;
}
set.add(t);
}
return true;
}
在Java标准库或任何知名库(Guava等(中,有这样的方法吗?
我确信Guava中不存在这样的方法。
你的方法基本上是好的;我会对它进行一些调整,使其稍微更清洁/更高效:
// T doesn't really do anything. A wildcard is sufficient.
public static boolean areAllUnique(Collection<?> collection) {
if (collection instanceof Set) {
return true;
}
HashSet<Object> set = new HashSet<>(collection.size());
for (Object t : collection) {
// add only returns true if the set is changed, so you don't need to
// do contains/add separately.
if (!set.add(t)) {
return false;
}
}
return true;
}
如果你想让API设计人员哭泣(因为谓词应该是无状态的(,你也可以更简洁地做同样的事情:
return collection instanceof Set
|| collection.stream().allMatch(new HashSet<>(collection.size())::add);