Search code examples
javalambdasetguavalambdaj

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. so should merge them to form 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?


Solution

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

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