如何检查 Java 8 Streams 中是否存在任何重复项? [英] How to check if exists any duplicate in Java 8 Streams?
问题描述
在 java 8 中,检查 List 是否包含任何重复项的最佳方法是什么?
In java 8, what's the best way to check if a List contains any duplicate?
我的想法是这样的:
list.size() != list.stream().distinct().count()
这是最好的方法吗?
推荐答案
您的代码需要遍历所有元素.如果你想确保没有重复的简单方法,比如
Your code would need to iterate over all elements. If you want to make sure that there are no duplicates simple method like
public static <T> boolean areAllUnique(List<T> list){
Set<T> set = new HashSet<>();
for (T t: list){
if (!set.add(t))
return false;
}
return true;
}
会更有效率,因为它可以在找到第一个非唯一元素时立即给你 false
.
would be more efficient since it can give you false
immediately when first non-unique element would be found.
此方法也可以使用 Stream#allMatch
也是短路的(对于第一个元素立即返回 false不满足提供的条件)
This method could also be rewritten as (assuming non-parallel streams and thread-safe environment) using Stream#allMatch
which also is short-circuit (returns false immediately for first element which doesn't fulfill provided condition)
public static <T> boolean areAllUnique(List<T> list){
Set<T> set = new HashSet<>();
return list.stream().allMatch(t -> set.add(t));
}
或作为评论中提到的@Holger
public static <T> boolean areAllUnique(List<T> list){
return list.stream().allMatch(new HashSet<>()::add);
}
这篇关于如何检查 Java 8 Streams 中是否存在任何重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!