[英]Compare sets inside a set
我有这样的一套:
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。
输出应如下所示:
[[Node[0], Node[1], Node[2], Node[6]], [Node[3], Node[4], Node[5]]]
有什么有效的方法吗?
您可以使用Collections.disjoint(Collection c1,Collection c2)来检查两个指定的集合没有共同的元素。
顺便说一句,确保您的Node
类实现了hashCode
并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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.