【问题标题】:How to calculate the intersection of two sets? [duplicate]如何计算两组的交集? [复制]
【发布时间】:2012-02-11 12:25:03
【问题描述】:

可能重复:
Efficiently finding the intersection of a variable number of sets of strings

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

Set<String> s1 = new HashSet<String>();

Set<String> s2 = new HashSet<String>();

S1 INT S2 ?

【问题讨论】:

  • 公平地说,这是一个比原来更好的问题。条理清晰,写得好,切中要害。尽管最终的答案是相同的,但另一个问题全是文字——而且关注的是效率,而不是简单地完成工作。但是,对于 Java 8+,这可能是更好的答案:stackoverflow.com/a/39902694/1339923

标签: java set intersection hashset


【解决方案1】:

使用SetretainAll()方法:

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

retainAll()javadoc 表示这正是您想要的:

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

【讨论】:

  • 对于希望在另一个 Collection 上使用 retainAll 的任何人,例如具有重复元素的列表,请注意。根据集合的内容,您可以抛出 UnsupportedOperationException,并且它也不会正确过滤频率(它保留左侧多重集中的任何和所有出现的值,无论它在右侧多重集中出现多少次)。
【解决方案2】:

是的,有retainAll 退房this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2020-07-14
    相关资源
    最近更新 更多