可能的重复:高效找到变量数的交集字符串集合
说,有两个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.
更多推荐
如何计算两个集合的交集?
发布评论