问题
可能重复:有效地找到可变数量的字符串集的交集
说,有两个Hashset,如何计算它们的交集?
Set<String> s1 = new HashSet<String>();
Set<String> s2 = new HashSet<String>();
S1 INT S2 ?
#1 热门回答(290 赞)
使用88091715的retainAll()
方法:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
如果要保留集合,请创建一个新集来保存集合:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
javadocofretainAll()
这正是你想要的:
仅保留此集合中包含在指定集合中的元素(可选操作)。换句话说,从该集合中删除未包含在指定集合中的所有元素。如果指定的集合也是一个集合,则此操作会有效地修改此集合,使其值为两个集合的交集。
#2 热门回答(32 赞)
是的,有retainAll
检查this
Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);