加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 如何计算两个以上HashSet之间的交集?

发布时间:2020-12-14 05:02:29 所属栏目:Java 来源:网络整理
导读:考虑下面的代码以及4个HashSets填充在其他地方的事实. 我的目标是包含所有4个HashSets中常见的所有元素. 我的问题是,首先,我做得对吗?其次,如果我做得对,有没有更好的方法呢?如果没有,那么我对此问题有什么解决方案? static SetString one=new HashSet();
考虑下面的代码以及4个HashSets填充在其他地方的事实.

我的目标是包含所有4个HashSets中常见的所有元素.

我的问题是,首先,我做得对吗?其次,如果我做得对,有没有更好的方法呢?如果没有,那么我对此问题有什么解决方案?

static Set<String> one=new HashSet<>();
static Set<String> two=new HashSet<>();
static Set<String> three=new HashSet<>();
static Set<String> four=new HashSet<>();

private static void createIntersectionQrels() {
    ArrayList<String> temp = new ArrayList<>();
    Set<String> interQrels = new HashSet<>();

    temp.addAll(one);
    one.retainAll(two);
    interQrels.addAll(one);
    one.addAll(temp);
    one.retainAll(three);
    interQrels.addAll(one);
    one.addAll(temp);
    one.retainAll(four);
    interQrels.addAll(one);
    one.addAll(temp);

    interQrels.retainAll(two);
    interQrels.retainAll(three);
    interQrels.retainAll(four);
}

解决方法

我想你可以简单地在第一组上调用retainAll(),使用第二,第三和第四组作为参数:
private static Set<String> getIntersectionSet() {
    // create a deep copy of one (in case you don't wish to modify it)
    Set<String> interQrels = new HashSet<>(one);

    interQrels.retainAll(two);     // intersection with two (and one)
    interQrels.retainAll(three);   // intersection with three (and two,one)
    interQrels.retainAll(four);    // intersection four (and three,two,one)

    return interQrels;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读