比较集合中的集合 [英] Compare sets inside a set

查看:134
本文介绍了比较集合中的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的一套:

Set<Set<Node>> NestedSet = new HashSet<Set<Node>>();

[[Node[0], Node[1], Node[2]], [Node[0], Node[2], Node[6]], [Node[3], Node[4], Node[5]]]

我想比较和合并嵌套集中的集合. [0,1,2]和[0,2,6]具有共同的元素.因此应将它们合并成0、1、2、6.

I want to compare and merge sets that are inside the nested set. [0,1,2] and [0,2,6] has element in common. so should merge them to form 0,1,2,6.

输出应如下所示:

[[Node[0], Node[1], Node[2], Node[6]], [Node[3], Node[4], Node[5]]]

有什么有效的方法吗?

推荐答案

您可以使用

You can use Collections.disjoint(Collection c1, Collection c2) to check two specified collections have no elements in common.

再次请确保您的Node类实现了hashCodeequals

Btw make sure your Node class implemented hashCode and equals

Set<Set<Node>> result = new HashSet<Set<Node>>();
for (Set<Node> s1 : NestedSet) {
    Optional<Set<Node>> findFirst = result.stream().filter(p -> !Collections.disjoint(s1, p)).findFirst();
    if (findFirst.isPresent()){
        findFirst.get().addAll(s1); 
    }
    else {
        result.add(s1);
    }
}

这篇关于比较集合中的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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