2017-04-26 47 views
1

我想測試一個可能的拓撲,它是一組開放集。要做到這一點,我需要找到聯合和交集的集合。這樣做我可以創建一個Generated Topology。我想我能找到,至少無需使用外部庫最好的 - 似乎谷歌有一個Guava庫多集的能力,是做一些事情,如following(最後的答案):Java中的聯合集和交集(生成拓撲)

Set<Set<String>> myCollection = new HashSet<>(); 

我不不知道是否值得嘗試學習Multiset的各種方法,當我可以以某種方式循環並將集合添加到「myCollection」時。對於使用諸如MultisetBag的東西真的有什麼好處的建議?

更具體地說我會子集的集合(超集),比方說{{A,B,D}, {B,C}}我們可以看到{A,B,D} U {B,C} = {A,B,C,D}${A,B,D} ∩ {B,C} = {B}$因此的{{A,B,D}, {B,C}, {B}, {A,B,C,D}}.新超的超集都不會得到非常大的,也許幾十元的最。

回答

1

A Multiset適用於需要可包含多個相同元素的Set(因爲Set只能容納每個元素中的一個)。

如果你想找到的多個Set S中集或交集,然後我建議使用谷歌的番石榴庫,它有以下方法,這將是對你有用的Sets.java

static <E> Sets.SetView<E> union(Set<? extends E> set1, Set<? extends E> set2) 
static <E> Sets.SetView<E> intersection(Set<E> set1, Set<?> set2) 

如果你不想使用番石榴,再有,你可以在Java中發現無論是工會和兩套交集方式:

Set<Integer> first = new HashSet<>(Arrays.asList(1, 3, 5, 7)); 
Set<Integer> second = new HashSet<>(Arrays.asList(2, 4, 6, 8)); 

// Creates a new Set as a copy of 'first' and then adds every element from 'second' into the new Set, creating a union. 
Set<Integer> union = new HashSet<>(first); 

union.addAll(second); 

System.out.println(union); 

>> {1, 2, 3, 4, 5, 6, 7, 8} 

// Creates a new Set as a copy of 'first' and then removes every element from the new Set that is not contained within 'second', creating an intersection. 
Set<Integer> intersection = new HashSet<>(first); 

intersection.retainAll(second); 

System.out.println(intersection); 

>> {} 
0

如果我明白你的問題科爾實際上,您需要一種方法來接收一組集合並添加任何集合,這些集合是一個或多個成員的聯合或一個或多個成員的交集。

如果這是正確的,那麼它肯定可以用標準Java完成 - 不需要Guava或其他庫。

寫作方法來尋找並集或交集是相當簡單:

Set<T> union(Set<Set<T>> sets) { 
    return sets.stream().reduce(new HashSet<>(), 
     (s1, s2) -> { 
      s1.addAll(s2); 
      return s1; 
     }); 
} 

交集是稍硬:你需要複製集,以避免改變他們:

Set<T> intersection(Set<Set<T>> sets) { 
    return sets.stream().map(HashSet::new).reduce(
     (s1, s2) -> { 
      s1.retainAll(s2); 
      return s1; 
     }); 
} 

而且更復雜位:對所有成員組合執行這些操作。

void topology(Set<Set<T>> sets) { 
    process(new HashSet<>(sets), sets); 
} 

private void process(Set<Set<T>> input, Set<Set<T>> output) { 
    if (!input.isEmpty()) { 
     output.add(union(input)); 
     output.add(intersection(input)); 
     input.stream().forEach(el1 -> 
      process(input.stream().filter(el2 -> !el1.equals(el2)) 
       .collect(toSet()), output)); 
    } 
} 

如果您需要進一步解釋這些方法,請在評論中告訴我。

我試圖與集合{{1,3,5},{2,3,7},{4,7,9}}和接收的結果:

[[], [1, 2, 3, 5, 7], [3], [4, 7, 9], [7], [1, 3, 5], [2, 3, 4, 7, 9], [2, 3, 7], [1, 3, 4, 5, 7, 9], [1, 2, 3, 4, 5, 7, 9]] 

我通過假定由於原始集的第一個元素和最後一個元素不重疊,因此您需要在結果中設置空集的問題的定義。