    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        @Override
    089        public TreeMap<C, V> get() {
    090          return new TreeMap<C, V>(comparator);
    091        }
    092        private static final long serialVersionUID = 0;
    093      }
    094
    095      /**
    096       * Creates an empty {@code TreeBasedTable} that uses the natural orderings
    097       * of both row and column keys.
    098       *
    099       * <p>The method signature specifies {@code R extends Comparable} with a raw
    100       * {@link Comparable}, instead of {@code R extends Comparable<? super R>},
    101       * and the same for {@code C}. That's necessary to support classes defined
    102       * without generics.
    103       */
    104      public static <R extends Comparable, C extends Comparable, V>
    105          TreeBasedTable<R, C, V> create() {
    106        return new TreeBasedTable<R, C, V>(Ordering.natural(),
    107            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,
    119          Comparator<? super C> columnComparator) {
    120        checkNotNull(rowComparator);
    121        checkNotNull(columnComparator);
    122        return new TreeBasedTable<R, C, V>(rowComparator, columnComparator);
    123      }
    124
    125      /**
    126       * Creates a {@code TreeBasedTable} with the same mappings and sort order
    127       * as the specified {@code TreeBasedTable}.
    128       */
    129      public static <R, C, V> TreeBasedTable<R, C, V> create(
    130          TreeBasedTable<R, C, ? extends V> table) {
    131        TreeBasedTable<R, C, V> result
    132            = new TreeBasedTable<R, C, V>(
    133                table.rowComparator(), table.columnComparator());
    134        result.putAll(table);
    135        return result;
    136      }
    137
    138      TreeBasedTable(Comparator<? super R> rowComparator,
    139          Comparator<? super C> columnComparator) {
    140        super(new TreeMap<R, Map<C, V>>(rowComparator),
    141            new Factory<C, V>(columnComparator));
    142        this.columnComparator = columnComparator;
    143      }
    144
    145      // TODO(jlevy): Move to StandardRowSortedTable?
    146
    147      /**
    148       * Returns the comparator that orders the rows. With natural ordering,
    149       * {@link Ordering#natural()} is returned.
    150       */
    151      public Comparator<? super R> rowComparator() {
    152        return rowKeySet().comparator();
    153      }
    154
    155      /**
    156       * Returns the comparator that orders the columns. With natural ordering,
    157       * {@link Ordering#natural()} is returned.
    158       */
    159      public Comparator<? super C> columnComparator() {
    160        return columnComparator;
    161      }
    162
    163      // TODO(user): make column return a SortedMap
    164
    165      /**
    166       * {@inheritDoc}
    167       *
    168       * <p>Because a {@code TreeBasedTable} has unique sorted values for a given
    169       * row, this method returns a {@link SortedMap}, instead of the {@link Map}
    170       * specified in the {@link Table} interface.
    171       * @since 10.0
    172       *     (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility"
    173       *     >mostly source-compatible</a> since 7.0)
    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        @Override 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        @Override 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        @Override public SortedMap<C, V> headMap(C toKey) {
    219          checkArgument(rangeContains(checkNotNull(toKey)));
    220          return new TreeRow(rowKey, lowerBound, toKey);
    221        }
    222
    223        @Override public SortedMap<C, V> tailMap(C fromKey) {
    224          checkArgument(rangeContains(checkNotNull(fromKey)));
    225          return new TreeRow(rowKey, fromKey, upperBound);
    226        }
    227
    228        @Override 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        @Override 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        @Override
    259        SortedMap<C, V> backingRowMap() {
    260          return (SortedMap<C, V>) super.backingRowMap();
    261        }
    262
    263        @Override
    264        SortedMap<C, V> computeBackingRowMap() {
    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          if (wholeRow() != null && wholeRow.isEmpty()) {
    281            backingMap.remove(rowKey);
    282            wholeRow = null;
    283            backingRowMap = null;
    284          }
    285        }
    286
    287        @Override public boolean containsKey(Object key) {
    288          return rangeContains(key) && super.containsKey(key);
    289        }
    290
    291        @Override public V put(C key, V value) {
    292          checkArgument(rangeContains(checkNotNull(key)));
    293          return super.put(key, value);
    294        }
    295      }
    296
    297      // rowKeySet() and rowMap() are defined here so they appear in the Javadoc.
    298
    299      @Override public SortedSet<R> rowKeySet() {
    300        return super.rowKeySet();
    301      }
    302
    303      @Override public SortedMap<R, Map<C, V>> rowMap() {
    304        return super.rowMap();
    305      }
    306
    307      // Overriding so NullPointerTester test passes.
    308
    309      @Override public boolean contains(
    310          @Nullable Object rowKey, @Nullable Object columnKey) {
    311        return super.contains(rowKey, columnKey);
    312      }
    313
    314      @Override public boolean containsColumn(@Nullable Object columnKey) {
    315        return super.containsColumn(columnKey);
    316      }
    317
    318      @Override public boolean containsRow(@Nullable Object rowKey) {
    319        return super.containsRow(rowKey);
    320      }
    321
    322      @Override public boolean containsValue(@Nullable Object value) {
    323        return super.containsValue(value);
    324      }
    325
    326      @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
    327        return super.get(rowKey, columnKey);
    328      }
    329
    330      @Override public boolean equals(@Nullable Object obj) {
    331        return super.equals(obj);
    332      }
    333
    334      @Override public V remove(
    335          @Nullable Object rowKey, @Nullable Object columnKey) {
    336        return super.remove(rowKey, columnKey);
    337      }
    338
    339      /**
    340       * Overridden column iterator to return columns values in globally sorted
    341       * order.
    342       */
    343      @Override
    344      Iterator<C> createColumnKeyIterator() {
    345        final Comparator<? super C> comparator = columnComparator();
    346
    347        final Iterator<C> merged =
    348            Iterators.mergeSorted(Iterables.transform(backingMap.values(),
    349                new Function<Map<C, V>, Iterator<C>>() {
    350                  @Override
    351                  public Iterator<C> apply(Map<C, V> input) {
    352                    return input.keySet().iterator();
    353                  }
    354                }), comparator);
    355
    356        return new AbstractIterator<C>() {
    357          C lastValue;
    358
    359          @Override
    360          protected C computeNext() {
    361            while (merged.hasNext()) {
    362              C next = merged.next();
    363              boolean duplicate =
    364                  lastValue != null && comparator.compare(next, lastValue) == 0;
    365
    366              // Keep looping till we find a non-duplicate value.
    367              if (!duplicate) {
    368                lastValue = next;
    369                return lastValue;
    370              }
    371            }
    372
    373            lastValue = null; // clear reference to unused data
    374            return endOfData();
    375          }
    376        };
    377      }
    378
    379      private static final long serialVersionUID = 0;
    380    }