001/* 002 * Copyright (C) 2008 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.google.common.collect; 018 019import static com.google.common.base.Preconditions.checkArgument; 020import static com.google.common.base.Preconditions.checkNotNull; 021import static com.google.common.collect.Iterables.transform; 022import static com.google.common.collect.Iterators.mergeSorted; 023import static java.util.Objects.requireNonNull; 024 025import com.google.common.annotations.GwtCompatible; 026import com.google.common.base.Supplier; 027import java.io.Serializable; 028import java.util.Comparator; 029import java.util.Iterator; 030import java.util.Map; 031import java.util.NoSuchElementException; 032import java.util.Set; 033import java.util.SortedMap; 034import java.util.SortedSet; 035import java.util.TreeMap; 036import javax.annotation.CheckForNull; 037 038/** 039 * Implementation of {@code Table} whose row keys and column keys are ordered by their natural 040 * ordering or by supplied comparators. When constructing a {@code TreeBasedTable}, you may provide 041 * comparators for the row keys and the column keys, or you may use natural ordering for both. 042 * 043 * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link #rowMap} method 044 * returns a {@link SortedMap}, instead of the {@link Set} and {@link Map} specified by the {@link 045 * Table} interface. 046 * 047 * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link #columnMap()} have 048 * iterators that don't support {@code remove()}. Otherwise, all optional operations are supported. 049 * Null row keys, columns keys, and values are not supported. 050 * 051 * <p>Lookups by row key are often faster than lookups by column key, because the data is stored in 052 * a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still runs 053 * quickly, since the row key is provided. However, {@code column(columnKey).size()} takes longer, 054 * since an iteration across all row keys occurs. 055 * 056 * <p>Because a {@code TreeBasedTable} has unique sorted values for a given row, both {@code 057 * row(rowKey)} and {@code rowMap().get(rowKey)} are {@link SortedMap} instances, instead of the 058 * {@link Map} specified in the {@link Table} interface. 059 * 060 * <p>Note that this implementation is not synchronized. If multiple threads access this table 061 * concurrently and one of the threads modifies the table, it must be synchronized externally. 062 * 063 * <p>See the Guava User Guide article on <a href= 064 * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>. 065 * 066 * @author Jared Levy 067 * @author Louis Wasserman 068 * @since 7.0 069 */ 070@GwtCompatible(serializable = true) 071@ElementTypesAreNonnullByDefault 072public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> { 073 private final Comparator<? super C> columnComparator; 074 075 private static class Factory<C, V> implements Supplier<Map<C, V>>, Serializable { 076 final Comparator<? super C> comparator; 077 078 Factory(Comparator<? super C> comparator) { 079 this.comparator = comparator; 080 } 081 082 @Override 083 public Map<C, V> get() { 084 return new TreeMap<>(comparator); 085 } 086 087 private static final long serialVersionUID = 0; 088 } 089 090 /** 091 * Creates an empty {@code TreeBasedTable} that uses the natural orderings of both row and column 092 * keys. 093 * 094 * <p>The method signature specifies {@code R extends Comparable} with a raw {@link Comparable}, 095 * instead of {@code R extends Comparable<? super R>}, and the same for {@code C}. That's 096 * necessary to support classes defined without generics. 097 */ 098 @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 099 public static <R extends Comparable, C extends Comparable, V> TreeBasedTable<R, C, V> create() { 100 return new TreeBasedTable<>(Ordering.natural(), Ordering.natural()); 101 } 102 103 /** 104 * Creates an empty {@code TreeBasedTable} that is ordered by the specified comparators. 105 * 106 * @param rowComparator the comparator that orders the row keys 107 * @param columnComparator the comparator that orders the column keys 108 */ 109 public static <R, C, V> TreeBasedTable<R, C, V> create( 110 Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { 111 checkNotNull(rowComparator); 112 checkNotNull(columnComparator); 113 return new TreeBasedTable<>(rowComparator, columnComparator); 114 } 115 116 /** 117 * Creates a {@code TreeBasedTable} with the same mappings and sort order as the specified {@code 118 * TreeBasedTable}. 119 */ 120 public static <R, C, V> TreeBasedTable<R, C, V> create(TreeBasedTable<R, C, ? extends V> table) { 121 TreeBasedTable<R, C, V> result = 122 new TreeBasedTable<>(table.rowComparator(), table.columnComparator()); 123 result.putAll(table); 124 return result; 125 } 126 127 TreeBasedTable(Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { 128 super(new TreeMap<R, Map<C, V>>(rowComparator), new Factory<C, V>(columnComparator)); 129 this.columnComparator = columnComparator; 130 } 131 132 // TODO(jlevy): Move to StandardRowSortedTable? 133 134 /** 135 * Returns the comparator that orders the rows. With natural ordering, {@link Ordering#natural()} 136 * is returned. 137 * 138 * @deprecated Use {@code table.rowKeySet().comparator()} instead. 139 */ 140 @Deprecated 141 public Comparator<? super R> rowComparator() { 142 /* 143 * requireNonNull is safe because the factories require non-null Comparators, which they pass on 144 * to the backing collections. 145 */ 146 return requireNonNull(rowKeySet().comparator()); 147 } 148 149 /** 150 * Returns the comparator that orders the columns. With natural ordering, {@link 151 * Ordering#natural()} is returned. 152 * 153 * @deprecated Store the {@link Comparator} alongside the {@link Table}. Or, if you know that the 154 * {@link Table} contains at least one value, you can retrieve the {@link Comparator} with: 155 * {@code ((SortedMap<C, V>) table.rowMap().values().iterator().next()).comparator();}. 156 */ 157 @Deprecated 158 public Comparator<? super C> columnComparator() { 159 return columnComparator; 160 } 161 162 // TODO(lowasser): make column return a SortedMap 163 164 /** 165 * {@inheritDoc} 166 * 167 * <p>Because a {@code TreeBasedTable} has unique sorted values for a given row, this method 168 * returns a {@link SortedMap}, instead of the {@link Map} specified in the {@link Table} 169 * interface. 170 * 171 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility" >mostly 172 * source-compatible</a> since 7.0) 173 */ 174 @Override 175 public SortedMap<C, V> row(R rowKey) { 176 return new TreeRow(rowKey); 177 } 178 179 private class TreeRow extends Row implements SortedMap<C, V> { 180 @CheckForNull final C lowerBound; 181 @CheckForNull final C upperBound; 182 183 TreeRow(R rowKey) { 184 this(rowKey, null, null); 185 } 186 187 TreeRow(R rowKey, @CheckForNull C lowerBound, @CheckForNull C upperBound) { 188 super(rowKey); 189 this.lowerBound = lowerBound; 190 this.upperBound = upperBound; 191 checkArgument( 192 lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); 193 } 194 195 @Override 196 public SortedSet<C> keySet() { 197 return new Maps.SortedKeySet<>(this); 198 } 199 200 @Override 201 public Comparator<? super C> comparator() { 202 return columnComparator(); 203 } 204 205 int compare(Object a, Object b) { 206 // pretend we can compare anything 207 @SuppressWarnings("unchecked") 208 Comparator<Object> cmp = (Comparator<Object>) comparator(); 209 return cmp.compare(a, b); 210 } 211 212 boolean rangeContains(@CheckForNull Object o) { 213 return o != null 214 && (lowerBound == null || compare(lowerBound, o) <= 0) 215 && (upperBound == null || compare(upperBound, o) > 0); 216 } 217 218 @Override 219 public SortedMap<C, V> subMap(C fromKey, C toKey) { 220 checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); 221 return new TreeRow(rowKey, fromKey, toKey); 222 } 223 224 @Override 225 public SortedMap<C, V> headMap(C toKey) { 226 checkArgument(rangeContains(checkNotNull(toKey))); 227 return new TreeRow(rowKey, lowerBound, toKey); 228 } 229 230 @Override 231 public SortedMap<C, V> tailMap(C fromKey) { 232 checkArgument(rangeContains(checkNotNull(fromKey))); 233 return new TreeRow(rowKey, fromKey, upperBound); 234 } 235 236 @Override 237 public C firstKey() { 238 updateBackingRowMapField(); 239 if (backingRowMap == null) { 240 throw new NoSuchElementException(); 241 } 242 return ((SortedMap<C, V>) backingRowMap).firstKey(); 243 } 244 245 @Override 246 public C lastKey() { 247 updateBackingRowMapField(); 248 if (backingRowMap == null) { 249 throw new NoSuchElementException(); 250 } 251 return ((SortedMap<C, V>) backingRowMap).lastKey(); 252 } 253 254 @CheckForNull transient SortedMap<C, V> wholeRow; 255 256 // If the row was previously empty, we check if there's a new row here every time we're queried. 257 void updateWholeRowField() { 258 if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { 259 wholeRow = (SortedMap<C, V>) backingMap.get(rowKey); 260 } 261 } 262 263 @Override 264 @CheckForNull 265 SortedMap<C, V> computeBackingRowMap() { 266 updateWholeRowField(); 267 SortedMap<C, V> map = wholeRow; 268 if (map != null) { 269 if (lowerBound != null) { 270 map = map.tailMap(lowerBound); 271 } 272 if (upperBound != null) { 273 map = map.headMap(upperBound); 274 } 275 return map; 276 } 277 return null; 278 } 279 280 @Override 281 void maintainEmptyInvariant() { 282 updateWholeRowField(); 283 if (wholeRow != null && wholeRow.isEmpty()) { 284 backingMap.remove(rowKey); 285 wholeRow = null; 286 backingRowMap = null; 287 } 288 } 289 290 @Override 291 public boolean containsKey(@CheckForNull Object key) { 292 return rangeContains(key) && super.containsKey(key); 293 } 294 295 @Override 296 @CheckForNull 297 public V put(C key, V value) { 298 checkArgument(rangeContains(checkNotNull(key))); 299 return super.put(key, value); 300 } 301 } 302 303 // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. 304 305 @Override 306 public SortedSet<R> rowKeySet() { 307 return super.rowKeySet(); 308 } 309 310 @Override 311 public SortedMap<R, Map<C, V>> rowMap() { 312 return super.rowMap(); 313 } 314 315 /** Overridden column iterator to return columns values in globally sorted order. */ 316 @Override 317 Iterator<C> createColumnKeyIterator() { 318 Comparator<? super C> comparator = columnComparator(); 319 320 Iterator<C> merged = 321 mergeSorted( 322 transform(backingMap.values(), (Map<C, V> input) -> input.keySet().iterator()), 323 comparator); 324 325 return new AbstractIterator<C>() { 326 @CheckForNull C lastValue; 327 328 @Override 329 @CheckForNull 330 protected C computeNext() { 331 while (merged.hasNext()) { 332 C next = merged.next(); 333 boolean duplicate = lastValue != null && comparator.compare(next, lastValue) == 0; 334 335 // Keep looping till we find a non-duplicate value. 336 if (!duplicate) { 337 lastValue = next; 338 return lastValue; 339 } 340 } 341 342 lastValue = null; // clear reference to unused data 343 return endOfData(); 344 } 345 }; 346 } 347 348 private static final long serialVersionUID = 0; 349}