当前位置: 代码网 > it编程>编程语言>Java > Java-两个集合取交集(4种方式)

Java-两个集合取交集(4种方式)

2024年07月28日 Java 我要评论
开发难免需要对集合进行操作,例如对两个集合取交集也是常见操作。下面就列举了几种对两个集合取交集的方法。

开发难免需要对集合进行操作,例如对两个集合取交集也是常见操作。下面就列举了几种对两个集合取交集的方法。

方式1:利用java8 stream流

   list<integer> list1 = arrays.aslist(1, 2, 3, 4, 5);
   list<integer> list2 = arrays.aslist(4, 5, 6, 7, 8);

   list<integer> intersection = list1.stream()
       .filter(list2::contains)
       .collect(collectors.tolist());

方式2:使用java的retainall()方法

   list<integer> list1 = new arraylist<>(arrays.aslist(1, 2, 3, 4, 5));
   list<integer> list2 = new arraylist<>(arrays.aslist(4, 5, 6, 7, 8));

   // 创建list1的副本以避免修改原始集合
   list<integer> copyoflist1 = new arraylist<>(list1);
   copyoflist1.retainall(list2);

   list<integer> intersection = copyoflist1;

注意:retainall()会改变原集合,所以通常需要先复制其中一个集合

方式3:使用apache commons collections

如果你的项目引入了apache commons collections库,你可以使用collectionutils.intersection()方法:

   list<integer> list1 = new arraylist<>(arrays.aslist(1, 2, 3, 4, 5));
   list<integer> list2 = new arraylist<>(arrays.aslist(4, 5, 6, 7, 8));

   list<integer> intersection = collectionutils.intersection(list1, list2);

方式4:使用java 8的并行流(parallel streams)

对于大数据量,可以利用并行流提高性能

   list<integer> list1 = ...;
   list<integer> list2 = ...;

   list<integer> intersection = list1.parallelstream()
       .filter(list2::contains)
       .collect(collectors.tolist());

注意:并行流可以利用多核处理器的优势,但是,如果集合大小较小,可能并不会带来显著的性能提升,反而会增加不必要的线程开销。

有更好的方式或想法,欢迎大家评论区留言,互相学习~

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com