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 org.checkerframework.checker.nullness.qual.Nullable; 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) 071public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> { 072 private final Comparator<? super C> columnComparator; 073 074 private static class Factory<C, V> implements Supplier<Map<C, V>>, Serializable { 075 final Comparator<? super C> comparator; 076 077 Factory(Comparator<? super C> comparator) { 078 this.comparator = comparator; 079 } 080 081 @Override 082 public Map<C, V> get() { 083 return new TreeMap<>(comparator); 084 } 085 086 private static final long serialVersionUID = 0; 087 } 088 089 /** 090 * Creates an empty {@code TreeBasedTable} that uses the natural orderings of both row and column 091 * keys. 092 * 093 * <p>The method signature specifies {@code R extends Comparable} with a raw {@link Comparable}, 094 * instead of {@code R extends Comparable<? super R>}, and the same for {@code C}. That's 095 * necessary to support classes defined without generics. 096 */ 097 @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 098 public static <R extends Comparable, C extends Comparable, V> TreeBasedTable<R, C, V> create() { 099 return new TreeBasedTable<>(Ordering.natural(), Ordering.natural()); 100 } 101 102 /** 103 * Creates an empty {@code TreeBasedTable} that is ordered by the specified comparators. 104 * 105 * @param rowComparator the comparator that orders the row keys 106 * @param columnComparator the comparator that orders the column keys 107 */ 108 public static <R, C, V> TreeBasedTable<R, C, V> create( 109 Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { 110 checkNotNull(rowComparator); 111 checkNotNull(columnComparator); 112 return new TreeBasedTable<>(rowComparator, columnComparator); 113 } 114 115 /** 116 * Creates a {@code TreeBasedTable} with the same mappings and sort order as the specified {@code 117 * TreeBasedTable}. 118 */ 119 public static <R, C, V> TreeBasedTable<R, C, V> create(TreeBasedTable<R, C, ? extends V> table) { 120 TreeBasedTable<R, C, V> result = 121 new TreeBasedTable<>(table.rowComparator(), table.columnComparator()); 122 result.putAll(table); 123 return result; 124 } 125 126 TreeBasedTable(Comparator<? super R> rowComparator, Comparator<? super C> columnComparator) { 127 super(new TreeMap<R, Map<C, V>>(rowComparator), new Factory<C, V>(columnComparator)); 128 this.columnComparator = columnComparator; 129 } 130 131 // TODO(jlevy): Move to StandardRowSortedTable? 132 133 /** 134 * Returns the comparator that orders the rows. With natural ordering, {@link Ordering#natural()} 135 * is returned. 136 * 137 * @deprecated Use {@code table.rowKeySet().comparator()} instead. 138 */ 139 @Deprecated 140 public Comparator<? super R> rowComparator() { 141 /* 142 * requireNonNull is safe because the factories require non-null Comparators, which they pass on 143 * to the backing collections. 144 */ 145 return requireNonNull(rowKeySet().comparator()); 146 } 147 148 /** 149 * Returns the comparator that orders the columns. With natural ordering, {@link 150 * Ordering#natural()} is returned. 151 * 152 * @deprecated Store the {@link Comparator} alongside the {@link Table}. Or, if you know that the 153 * {@link Table} contains at least one value, you can retrieve the {@link Comparator} with: 154 * {@code ((SortedMap<C, V>) table.rowMap().values().iterator().next()).comparator();}. 155 */ 156 @Deprecated 157 public Comparator<? super C> columnComparator() { 158 return columnComparator; 159 } 160 161 // TODO(lowasser): make column return a SortedMap 162 163 /** 164 * {@inheritDoc} 165 * 166 * <p>Because a {@code TreeBasedTable} has unique sorted values for a given row, this method 167 * returns a {@link SortedMap}, instead of the {@link Map} specified in the {@link Table} 168 * interface. 169 * 170 * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility" >mostly 171 * source-compatible</a> since 7.0) 172 */ 173 @Override 174 public SortedMap<C, V> row(R rowKey) { 175 return new TreeRow(rowKey); 176 } 177 178 private class TreeRow extends Row implements SortedMap<C, V> { 179 final @Nullable C lowerBound; 180 final @Nullable C upperBound; 181 182 TreeRow(R rowKey) { 183 this(rowKey, null, null); 184 } 185 186 TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) { 187 super(rowKey); 188 this.lowerBound = lowerBound; 189 this.upperBound = upperBound; 190 checkArgument( 191 lowerBound == null || upperBound == null || compare(lowerBound, upperBound) <= 0); 192 } 193 194 @Override 195 public SortedSet<C> keySet() { 196 return new Maps.SortedKeySet<>(this); 197 } 198 199 @Override 200 public Comparator<? super C> comparator() { 201 return columnComparator(); 202 } 203 204 int compare(Object a, Object b) { 205 // pretend we can compare anything 206 @SuppressWarnings("unchecked") 207 Comparator<Object> cmp = (Comparator<Object>) comparator(); 208 return cmp.compare(a, b); 209 } 210 211 boolean rangeContains(@Nullable Object o) { 212 return o != null 213 && (lowerBound == null || compare(lowerBound, o) <= 0) 214 && (upperBound == null || compare(upperBound, o) > 0); 215 } 216 217 @Override 218 public SortedMap<C, V> subMap(C fromKey, C toKey) { 219 checkArgument(rangeContains(checkNotNull(fromKey)) && rangeContains(checkNotNull(toKey))); 220 return new TreeRow(rowKey, fromKey, toKey); 221 } 222 223 @Override 224 public SortedMap<C, V> headMap(C toKey) { 225 checkArgument(rangeContains(checkNotNull(toKey))); 226 return new TreeRow(rowKey, lowerBound, toKey); 227 } 228 229 @Override 230 public SortedMap<C, V> tailMap(C fromKey) { 231 checkArgument(rangeContains(checkNotNull(fromKey))); 232 return new TreeRow(rowKey, fromKey, upperBound); 233 } 234 235 @Override 236 public C firstKey() { 237 updateBackingRowMapField(); 238 if (backingRowMap == null) { 239 throw new NoSuchElementException(); 240 } 241 return ((SortedMap<C, V>) backingRowMap).firstKey(); 242 } 243 244 @Override 245 public C lastKey() { 246 updateBackingRowMapField(); 247 if (backingRowMap == null) { 248 throw new NoSuchElementException(); 249 } 250 return ((SortedMap<C, V>) backingRowMap).lastKey(); 251 } 252 253 transient @Nullable SortedMap<C, V> wholeRow; 254 255 // If the row was previously empty, we check if there's a new row here every time we're queried. 256 void updateWholeRowField() { 257 if (wholeRow == null || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) { 258 wholeRow = (SortedMap<C, V>) backingMap.get(rowKey); 259 } 260 } 261 262 @Override 263 @Nullable SortedMap<C, V> computeBackingRowMap() { 264 updateWholeRowField(); 265 SortedMap<C, V> map = wholeRow; 266 if (map != null) { 267 if (lowerBound != null) { 268 map = map.tailMap(lowerBound); 269 } 270 if (upperBound != null) { 271 map = map.headMap(upperBound); 272 } 273 return map; 274 } 275 return null; 276 } 277 278 @Override 279 void maintainEmptyInvariant() { 280 updateWholeRowField(); 281 if (wholeRow != null && wholeRow.isEmpty()) { 282 backingMap.remove(rowKey); 283 wholeRow = null; 284 backingRowMap = null; 285 } 286 } 287 288 @Override 289 public boolean containsKey(@Nullable Object key) { 290 return rangeContains(key) && super.containsKey(key); 291 } 292 293 @Override 294 public @Nullable V put(C key, V value) { 295 checkArgument(rangeContains(checkNotNull(key))); 296 return super.put(key, value); 297 } 298 } 299 300 // rowKeySet() and rowMap() are defined here so they appear in the Javadoc. 301 302 @Override 303 public SortedSet<R> rowKeySet() { 304 return super.rowKeySet(); 305 } 306 307 @Override 308 public SortedMap<R, Map<C, V>> rowMap() { 309 return super.rowMap(); 310 } 311 312 /** Overridden column iterator to return columns values in globally sorted order. */ 313 @Override 314 Iterator<C> createColumnKeyIterator() { 315 Comparator<? super C> comparator = columnComparator(); 316 317 Iterator<C> merged = 318 mergeSorted( 319 transform(backingMap.values(), (Map<C, V> input) -> input.keySet().iterator()), 320 comparator); 321 322 return new AbstractIterator<C>() { 323 @Nullable C lastValue; 324 325 @Override 326 protected @Nullable C computeNext() { 327 while (merged.hasNext()) { 328 C next = merged.next(); 329 boolean duplicate = lastValue != null && comparator.compare(next, lastValue) == 0; 330 331 // Keep looping till we find a non-duplicate value. 332 if (!duplicate) { 333 lastValue = next; 334 return lastValue; 335 } 336 } 337 338 lastValue = null; // clear reference to unused data 339 return endOfData(); 340 } 341 }; 342 } 343 344 private static final long serialVersionUID = 0; 345}