简体   繁体   English

比较集合中的集合

[英]Compare sets inside a set

I have a set like this : 我有这样的一套:

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]]]

I want to compare and merge sets that are inside the nested set. 我想比较和合并嵌套集中的集合。 [0,1,2] and [0,2,6] has element in common. [0,1,2]和[0,2,6]具有共同的元素。 so should merge them to form 0,1,2,6. 因此应将它们合并为0、1、2、6。

The output should be like this: 输出应如下所示:

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

Is there any efficient way? 有什么有效的方法吗?

You can use Collections.disjoint(Collection c1, Collection c2) to check two specified collections have no elements in common. 您可以使用Collections.disjoint(Collection c1,Collection c2)来检查两个指定的集合没有共同的元素。

Btw make sure your Node class implemented hashCode and equals 顺便说一句,确保您的Node类实现了hashCodeequals

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM