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