如何计算两组的交集? [英] How to calculate the intersection of two sets?

查看:112
本文介绍了如何计算两组的交集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

有效地查找可变数量的字符串集合的交集

说,有两个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() Set

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

如果要保留集合,请创建 new 设置为保持交集:

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);

retainAll()的/api/java/util/Set.html#retainAll%28java.util.Collection%29\">javadoc 说它正是你想要的:

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.

这篇关于如何计算两组的交集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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