如何计算两个集合的交集?

编程入门 行业动态 更新时间:2024-10-26 01:19:01
本文介绍了如何计算两个集合的交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能的重复:高效找到变量数的交集字符串集合

说,有两个Hashset,如何计算它们的交集?

Say, have two Hashset, how to calculate the intersection of them?

Set<String> s1 = new HashSet<String>(); Set<String> s2 = new HashSet<String>(); S1 INT S2 ?

推荐答案

使用 retainAll()方法retainAll%28java.util.Collection%29">retainAll()java/util/Set.html">Set:

Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both sets

如果你想保留集合,创建一个新集合来保存交集:

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2);

javadoc retainAll() 说这正是你想要的:

The javadoc of retainAll() says it's exactly what you want:

仅保留此集合中包含在指定集合中的元素(可选操作).换句话说,从这个集合中删除所有不包含在指定集合中的元素.如果指定的集合也是一个集合,这个操作有效地修改了这个集合,使它的值是两个集合的交集.

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.

更多推荐

如何计算两个集合的交集?

本文发布于:2023-11-29 18:31:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647247.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!