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

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

问题描述

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

说,有两个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.

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

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