如何检查在Java 8 Streams中是否存在任何重复? [英] How to check if exists any duplicate in Java 8 Streams?

查看:3720
本文介绍了如何检查在Java 8 Streams中是否存在任何重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在java 8中,检查列表是否包含任何重复的最佳方法是什么?我的想法是这样的:

  list.size()!= list.stream()。distinct()。count()

这是最好的方法吗?

解决方案

你的代码需要迭代所有元素。如果你想确保没有重复的简单方法,如

  public static< T> boolean containsUnique(List< T> list){
Set< T> set = new HashSet(); (t t:list)

{
if(!set.add(t))
return false;
}

返回true;
}

将更有效率。



此方法也可以被重写为(假设非并行流和线程安全环境)

  public static< ; T> boolean containsUnique(List< T> list){
Set< T> set = new HashSet();
return list.stream()。allMatch(t - > set.add(t));
}

或作为 @ Holger 在评论中提到

  public static< T> boolean containsUnique(List< T> list){
return list.stream()。allMatch(new HashSet<>():: add);
}


In java 8, what's the best way to check if a List contains any duplicate?

My idea was something like:

list.size() != list.stream().distinct().count()

Is it the best way?

解决方案

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 containsUnique(List<T> list){
    Set<T> set = new HashSet<>();

    for (T t: list){
        if (!set.add(t))
            return false;
    }

    return true;
}

would be more efficient.

This method could also be rewritten as (assuming non-parallel streams and thread-safe environment)

public static <T> boolean containsUnique(List<T> list){
    Set<T> set = new HashSet<>();
    return list.stream().allMatch(t -> set.add(t));
}

or as @Holger mentioned in comment

public static <T> boolean containsUnique(List<T> list){
    return list.stream().allMatch(new HashSet<>()::add);
}

这篇关于如何检查在Java 8 Streams中是否存在任何重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆