Compare sets inside a set

我与影子孤独终老i 提交于 2019-12-22 01:32:52

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34963632/compare-sets-inside-a-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!