15 package com.cloudera.impala.util;
17 import java.util.Collection;
18 import java.util.Iterator;
22 import com.google.common.collect.Maps;
23 import com.google.common.collect.Sets;
32 public class DisjointSet<T> {
34 private final Map<T, Set<T>> itemSets_ = Maps.newHashMap();
35 private final Set<Set<T>> uniqueSets_ = Sets.newHashSet();
41 public Set<T>
get(T item) {
return itemSets_.get(item); }
43 public Set<Set<T>>
getSets() {
return uniqueSets_; }
50 if (itemSets_.containsKey(item)) {
51 throw new IllegalStateException(
52 "Item set for item already exists: " + item.toString());
54 Set<T> s = Sets.newHashSet(item);
55 itemSets_.put(item, s);
66 public boolean union(T a, T b) {
67 Set<T> aItems = itemSets_.get(a);
68 Set<T> bItems = itemSets_.get(b);
70 if (aItems != null && bItems != null && aItems == bItems)
return false;
73 if (a.equals(b) && aItems == null) {
79 if (aItems == null) aItems = makeSet(a);
80 if (bItems == null) bItems = makeSet(b);
83 Set<T> mergedItems = aItems;
85 Set<T> updateItems = bItems;
86 if (bItems.size() > aItems.size()) {
90 for (T item: updateItems) {
91 mergedItems.add(item);
92 itemSets_.put(item, mergedItems);
94 uniqueSets_.remove(updateItems);
103 if (items.isEmpty())
return false;
104 Iterator<T> it = items.iterator();
108 if (
get(head) != null)
return false;
112 boolean result =
false;
113 while(it.hasNext()) {
114 boolean changed =
union(head, it.next());
115 result = result || changed;
125 Set<Set<T>> validatedSets = Sets.newHashSet();
126 for (Set<T> itemSet: itemSets_.values()) {
128 if (validatedSets.contains(itemSet))
continue;
131 for (T item: itemSet) {
132 if (itemSet != itemSets_.get(item)) {
133 throw new IllegalStateException(
"DisjointSet is in an inconsistent state.");
136 validatedSets.add(itemSet);
boolean bulkUnion(Collection< T > items)
Set< Set< T > > getSets()