ped*_*o91 45 java duplicates java-8 java-stream
在java 8中,检查List是否包含任何重复的最佳方法是什么?
我的想法是这样的:
list.size() != list.stream().distinct().count()
Run Code Online (Sandbox Code Playgroud)
这是最好的方式吗?
Psh*_*emo 47
您的代码需要遍历所有元素.如果你想确保没有重复的简单方法,比如
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;
}
Run Code Online (Sandbox Code Playgroud)
会更有效率.
此方法也可以重写为(假设非并行流和线程安全的环境)
public static <T> boolean areAllUnique(List<T> list){
Set<T> set = new HashSet<>();
return list.stream().allMatch(t -> set.add(t));
}
Run Code Online (Sandbox Code Playgroud)
或者@Holger在评论中提到
public static <T> boolean areAllUnique(List<T> list){
return list.stream().allMatch(new HashSet<>()::add);
}
Run Code Online (Sandbox Code Playgroud)
Sas*_*sha 11
我使用了以下内容:
1 return list.size() == new HashSet<>(list).size();.
我不确定它与:
2.return list.size() == list.stream().distinct().count();
和
3. return list.stream().sequential().allMatch(new HashSet<>()::add);
在性能方面的比较.
最后一个(#3)不仅可以处理集合(例如列表),还可以处理流(没有明确地收集它们).
更新:最后一个(#3)似乎是最好的,不仅因为它可以处理纯流,而且因为它在第一个副本上停止(而#1和#2总是迭代直到结束) - 作为@Pshemo 评论说.
您可以使用计数收集器。
Stream.of(1, 3, 4, 6, 7, 5, 6)
.collect(Collectors.groupingBy(
Function.identity(), Collectors.counting()))
.entrySet().stream().anyMatch(e -> e.getValue() > 1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35578 次 |
| 最近记录: |