簡體   English   中英

比較集合中的集合

[英]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類實現了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