如何用Stream API进行去重操作

发布时间:2025-02-13 21:10:10 作者:小樊
来源:亿速云 阅读:93

在Java中,使用Stream API进行去重操作可以通过以下几种方法实现:

  1. 使用distinct()方法:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamDistinctExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);

        List<Integer> distinctNumbers = numbers.stream()
                                              .distinct()
                                              .collect(Collectors.toList());

        System.out.println(distinctNumbers);
    }
}
  1. 使用Collectors.toSet()方法:
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class StreamDistinctExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);

        Set<Integer> distinctNumbers = numbers.stream()
                                              .collect(Collectors.toSet());

        System.out.println(distinctNumbers);
    }
}
  1. 使用Collectors.toCollection()方法:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamDistinctExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);

        List<Integer> distinctNumbers = numbers.stream()
                                              .collect(Collectors.toCollection(() -> new TreeSet<>()));

        System.out.println(distinctNumbers);
    }
}

注意:在使用这些方法时,请确保你的对象实现了equals()hashCode()方法,以便正确地进行比较和去重。

推荐阅读:
  1. Java中List去重和Stream去重的示例分析
  2. 手把手带你体验Stream流

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Stream API中如何进行映射操作

下一篇:Stream API中如何进行连接操作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》