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
017 package com.google.common.collect;
018
019 import static com.google.common.base.Preconditions.checkArgument;
020 import static com.google.common.base.Preconditions.checkNotNull;
021
022 import com.google.common.annotations.Beta;
023 import com.google.common.annotations.GwtCompatible;
024 import com.google.common.base.Function;
025 import com.google.common.base.Supplier;
026
027 import java.io.Serializable;
028 import java.util.Comparator;
029 import java.util.Iterator;
030 import java.util.Map;
031 import java.util.NoSuchElementException;
032 import java.util.Set;
033 import java.util.SortedMap;
034 import java.util.SortedSet;
035 import java.util.TreeMap;
036
037 import javax.annotation.Nullable;
038
039 /**
040 * Implementation of {@code Table} whose row keys and column keys are ordered
041 * by their natural ordering or by supplied comparators. When constructing a
042 * {@code TreeBasedTable}, you may provide comparators for the row keys and
043 * the column keys, or you may use natural ordering for both.
044 *
045 * <p>The {@link #rowKeySet} method returns a {@link SortedSet} and the {@link
046 * #rowMap} method returns a {@link SortedMap}, instead of the {@link Set} and
047 * {@link Map} specified by the {@link Table} interface.
048 *
049 * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link
050 * #columnMap()} have iterators that don't support {@code remove()}. Otherwise,
051 * all optional operations are supported. Null row keys, columns keys, and
052 * values are not supported.
053 *
054 * <p>Lookups by row key are often faster than lookups by column key, because
055 * the data is stored in a {@code Map<R, Map<C, V>>}. A method call like {@code
056 * column(columnKey).get(rowKey)} still runs quickly, since the row key is
057 * provided. However, {@code column(columnKey).size()} takes longer, since an
058 * iteration across all row keys occurs.
059 *
060 * <p>Because a {@code TreeBasedTable} has unique sorted values for a given
061 * row, both {@code row(rowKey)} and {@code rowMap().get(rowKey)} are {@link
062 * SortedMap} instances, instead of the {@link Map} specified in the {@link
063 * Table} interface.
064 *
065 * <p>Note that this implementation is not synchronized. If multiple threads
066 * access this table concurrently and one of the threads modifies the table, it
067 * must be synchronized externally.
068 *
069 * <p>See the Guava User Guide article on <a href=
070 * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table">
071 * {@code Table}</a>.
072 *
073 * @author Jared Levy
074 * @author Louis Wasserman
075 * @since 7.0
076 */
077 @GwtCompatible(serializable = true)
078 @Beta
079 public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> {
080 private final Comparator<? super C> columnComparator;
081
082 private static class Factory<C, V>
083 implements Supplier<TreeMap<C, V>>, Serializable {
084 final Comparator<? super C> comparator;
085 Factory(Comparator<? super C> comparator) {
086 this.comparator = comparator;
087 }
088 public TreeMap<C, V> get() {
089 return new TreeMap<C, V>(comparator);
090 }
091 private static final long serialVersionUID = 0;
092 }
093
094 /**
095 * Creates an empty {@code TreeBasedTable} that uses the natural orderings
096 * of both row and column keys.
097 *
098 * <p>The method signature specifies {@code R extends Comparable} with a raw
099 * {@link Comparable}, instead of {@code R extends Comparable<? super R>},
100 * and the same for {@code C}. That's necessary to support classes defined
101 * without generics.
102 */
103 public static <R extends Comparable, C extends Comparable, V>
104 TreeBasedTable<R, C, V> create() {
105 return new TreeBasedTable<R, C, V>(Ordering.natural(),
106 Ordering.natural());
107 }
108
109 /**
110 * Creates an empty {@code TreeBasedTable} that is ordered by the specified
111 * comparators.
112 *
113 * @param rowComparator the comparator that orders the row keys
114 * @param columnComparator the comparator that orders the column keys
115 */
116 public static <R, C, V> TreeBasedTable<R, C, V> create(
117 Comparator<? super R> rowComparator,
118 Comparator<? super C> columnComparator) {
119 checkNotNull(rowComparator);
120 checkNotNull(columnComparator);
121 return new TreeBasedTable<R, C, V>(rowComparator, columnComparator);
122 }
123
124 /**
125 * Creates a {@code TreeBasedTable} with the same mappings and sort order
126 * as the specified {@code TreeBasedTable}.
127 */
128 public static <R, C, V> TreeBasedTable<R, C, V> create(
129 TreeBasedTable<R, C, ? extends V> table) {
130 TreeBasedTable<R, C, V> result
131 = new TreeBasedTable<R, C, V>(
132 table.rowComparator(), table.columnComparator());
133 result.putAll(table);
134 return result;
135 }
136
137 TreeBasedTable(Comparator<? super R> rowComparator,
138 Comparator<? super C> columnComparator) {
139 super(new TreeMap<R, Map<C, V>>(rowComparator),
140 new Factory<C, V>(columnComparator));
141 this.columnComparator = columnComparator;
142 }
143
144 // TODO(jlevy): Move to StandardRowSortedTable?
145
146 /**
147 * Returns the comparator that orders the rows. With natural ordering,
148 * {@link Ordering#natural()} is returned.
149 */
150 public Comparator<? super R> rowComparator() {
151 return rowKeySet().comparator();
152 }
153
154 /**
155 * Returns the comparator that orders the columns. With natural ordering,
156 * {@link Ordering#natural()} is returned.
157 */
158 public Comparator<? super C> columnComparator() {
159 return columnComparator;
160 }
161
162 // TODO(user): make column return a SortedMap
163
164 /**
165 * {@inheritDoc}
166 *
167 * <p>Because a {@code TreeBasedTable} has unique sorted values for a given
168 * row, this method returns a {@link SortedMap}, instead of the {@link Map}
169 * specified in the {@link Table} interface.
170 * @since 10.0
171 * (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
172 * >mostly source-compatible</a> since 7.0)
173 */
174
175 @Override
176 public SortedMap<C, V> row(R rowKey) {
177 return new TreeRow(rowKey);
178 }
179
180 private class TreeRow extends Row implements SortedMap<C, V> {
181 @Nullable final C lowerBound;
182 @Nullable final C upperBound;
183
184 TreeRow(R rowKey) {
185 this(rowKey, null, null);
186 }
187
188 TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) {
189 super(rowKey);
190 this.lowerBound = lowerBound;
191 this.upperBound = upperBound;
192 checkArgument(lowerBound == null || upperBound == null
193 || compare(lowerBound, upperBound) <= 0);
194 }
195
196 public Comparator<? super C> comparator() {
197 return columnComparator();
198 }
199
200 int compare(Object a, Object b) {
201 // pretend we can compare anything
202 @SuppressWarnings({"rawtypes", "unchecked"})
203 Comparator<Object> cmp = (Comparator) comparator();
204 return cmp.compare(a, b);
205 }
206
207 boolean rangeContains(@Nullable Object o) {
208 return o != null && (lowerBound == null || compare(lowerBound, o) <= 0)
209 && (upperBound == null || compare(upperBound, o) > 0);
210 }
211
212 public SortedMap<C, V> subMap(C fromKey, C toKey) {
213 checkArgument(rangeContains(checkNotNull(fromKey))
214 && rangeContains(checkNotNull(toKey)));
215 return new TreeRow(rowKey, fromKey, toKey);
216 }
217
218 public SortedMap<C, V> headMap(C toKey) {
219 checkArgument(rangeContains(checkNotNull(toKey)));
220 return new TreeRow(rowKey, lowerBound, toKey);
221 }
222
223 public SortedMap<C, V> tailMap(C fromKey) {
224 checkArgument(rangeContains(checkNotNull(fromKey)));
225 return new TreeRow(rowKey, fromKey, upperBound);
226 }
227
228 public C firstKey() {
229 SortedMap<C, V> backing = backingRowMap();
230 if (backing == null) {
231 throw new NoSuchElementException();
232 }
233 return backingRowMap().firstKey();
234 }
235
236 public C lastKey() {
237 SortedMap<C, V> backing = backingRowMap();
238 if (backing == null) {
239 throw new NoSuchElementException();
240 }
241 return backingRowMap().lastKey();
242 }
243
244 transient SortedMap<C, V> wholeRow;
245
246 /*
247 * If the row was previously empty, we check if there's a new row here every
248 * time we're queried.
249 */
250 SortedMap<C, V> wholeRow() {
251 if (wholeRow == null
252 || (wholeRow.isEmpty() && backingMap.containsKey(rowKey))) {
253 wholeRow = (SortedMap<C, V>) backingMap.get(rowKey);
254 }
255 return wholeRow;
256 }
257
258
259 @Override
260 SortedMap<C, V> backingRowMap() {
261 return (SortedMap<C, V>) super.backingRowMap();
262 }
263
264
265 @Override
266 SortedMap<C, V> computeBackingRowMap() {
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
281 @Override
282 void maintainEmptyInvariant() {
283 if (wholeRow() != null && wholeRow.isEmpty()) {
284 backingMap.remove(rowKey);
285 wholeRow = null;
286 backingRowMap = null;
287 }
288 }
289
290
291 @Override
292 public boolean containsKey(Object key) {
293 return rangeContains(key) && super.containsKey(key);
294 }
295
296
297 @Override
298 public V put(C key, V value) {
299 checkArgument(rangeContains(checkNotNull(key)));
300 return super.put(key, value);
301 }
302 }
303
304 // rowKeySet() and rowMap() are defined here so they appear in the Javadoc.
305
306
307 @Override
308 public SortedSet<R> rowKeySet() {
309 return super.rowKeySet();
310 }
311
312
313 @Override
314 public SortedMap<R, Map<C, V>> rowMap() {
315 return super.rowMap();
316 }
317
318 // Overriding so NullPointerTester test passes.
319
320
321 @Override
322 public boolean contains(
323 @Nullable Object rowKey, @Nullable Object columnKey) {
324 return super.contains(rowKey, columnKey);
325 }
326
327
328 @Override
329 public boolean containsColumn(@Nullable Object columnKey) {
330 return super.containsColumn(columnKey);
331 }
332
333
334 @Override
335 public boolean containsRow(@Nullable Object rowKey) {
336 return super.containsRow(rowKey);
337 }
338
339
340 @Override
341 public boolean containsValue(@Nullable Object value) {
342 return super.containsValue(value);
343 }
344
345
346 @Override
347 public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
348 return super.get(rowKey, columnKey);
349 }
350
351
352 @Override
353 public boolean equals(@Nullable Object obj) {
354 return super.equals(obj);
355 }
356
357
358 @Override
359 public V remove(
360 @Nullable Object rowKey, @Nullable Object columnKey) {
361 return super.remove(rowKey, columnKey);
362 }
363
364 /**
365 * Overridden column iterator to return columns values in globally sorted
366 * order.
367 */
368
369 @Override
370 Iterator<C> createColumnKeyIterator() {
371 final Comparator<? super C> comparator = columnComparator();
372
373 final Iterator<C> merged =
374 Iterators.mergeSorted(Iterables.transform(backingMap.values(),
375 new Function<Map<C, V>, Iterator<C>>() {
376 public Iterator<C> apply(Map<C, V> input) {
377 return input.keySet().iterator();
378 }
379 }), comparator);
380
381 return new AbstractIterator<C>() {
382 C lastValue;
383
384
385 @Override
386 protected C computeNext() {
387 while (merged.hasNext()) {
388 C next = merged.next();
389 boolean duplicate =
390 lastValue != null && comparator.compare(next, lastValue) == 0;
391
392 // Keep looping till we find a non-duplicate value.
393 if (!duplicate) {
394 lastValue = next;
395 return lastValue;
396 }
397 }
398
399 lastValue = null; // clear reference to unused data
400 return endOfData();
401 }
402 };
403 }
404
405 private static final long serialVersionUID = 0;
406 }