Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.collect;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.Map;
 import java.util.Set;
 
 import  javax.annotation.Nullable;

Implementation of Table whose row keys and column keys are ordered by their natural ordering or by supplied comparators. When constructing a TreeBasedTable, you may provide comparators for the row keys and the column keys, or you may use natural ordering for both.

The rowKeySet method returns a SortedSet and the rowMap method returns a SortedMap, instead of the Set and Map specified by the Table interface.

The views returned by column, columnKeySet(), and columnMap() have iterators that don't support remove(). Otherwise, all optional operations are supported. Null row keys, columns keys, and values are not supported.

Lookups by row key are often faster than lookups by column key, because the data is stored in a Map<R, Map<C, V>>. A method call like column(columnKey).get(rowKey) still runs quickly, since the row key is provided. However, column(columnKey).size() takes longer, since an iteration across all row keys occurs.

Because a TreeBasedTable has unique sorted values for a given row, both row(rowKey) and rowMap().get(rowKey) are SortedMap instances, instead of the Map specified in the Table interface.

Note that this implementation is not synchronized. If multiple threads access this table concurrently and one of the threads modifies the table, it must be synchronized externally.

See the Guava User Guide article on Table.

Author(s):
Jared Levy
Louis Wasserman
Since:
7.0
 
 @GwtCompatible(serializable = true)
 public class TreeBasedTable<R, C, V> extends StandardRowSortedTable<R, C, V> {
   private final Comparator<? super C> columnComparator;
 
   private static class Factory<C, V>
       implements Supplier<TreeMap<C, V>>, Serializable {
     final Comparator<? super C> comparator;
     Factory(Comparator<? super C> comparator) {
       this. = comparator;
     }
     @Override
     public TreeMap<C, V> get() {
       return new TreeMap<C, V>();
     }
     private static final long serialVersionUID = 0;
   }

  
Creates an empty TreeBasedTable that uses the natural orderings of both row and column keys.

The method signature specifies R extends Comparable with a raw Comparable, instead of R extends Comparable<? super R>, and the same for C. That's necessary to support classes defined without generics.

  public static <R extends Comparable, C extends Comparable, V>
      TreeBasedTable<R, C, V> create() {
    return new TreeBasedTable<R, C, V>(Ordering.natural(),
        Ordering.natural());
  }

  
Creates an empty TreeBasedTable that is ordered by the specified comparators.

Parameters:
rowComparator the comparator that orders the row keys
columnComparator the comparator that orders the column keys
  public static <R, C, V> TreeBasedTable<R, C, V> create(
      Comparator<? super R> rowComparator,
      Comparator<? super C> columnComparator) {
    checkNotNull(rowComparator);
    checkNotNull(columnComparator);
    return new TreeBasedTable<R, C, V>(rowComparatorcolumnComparator);
  }

  
Creates a TreeBasedTable with the same mappings and sort order as the specified TreeBasedTable.
  public static <R, C, V> TreeBasedTable<R, C, V> create(
      TreeBasedTable<R, C, ? extends V> table) {
    TreeBasedTable<R, C, V> result
        = new TreeBasedTable<R, C, V>(
            table.rowComparator(), table.columnComparator());
    result.putAll(table);
    return result;
  }
  TreeBasedTable(Comparator<? super R> rowComparator,
      Comparator<? super C> columnComparator) {
    super(new TreeMap<R, Map<C, V>>(rowComparator),
        new Factory<C, V>(columnComparator));
    this. = columnComparator;
  }
  // TODO(jlevy): Move to StandardRowSortedTable?

  
Returns the comparator that orders the rows. With natural ordering, Ordering.natural() is returned.
  public Comparator<? super R> rowComparator() {
    return rowKeySet().comparator();
  }

  
Returns the comparator that orders the columns. With natural ordering, Ordering.natural() is returned.
  public Comparator<? super C> columnComparator() {
    return ;
  }
  // TODO(user): make column return a SortedMap

  

Because a TreeBasedTable has unique sorted values for a given row, this method returns a SortedMap, instead of the Map specified in the Table interface.

Since:
10.0 (mostly source-compatible since 7.0)
  public SortedMap<C, V> row(R rowKey) {
    return new TreeRow(rowKey);
  }
  private class TreeRow extends Row implements SortedMap<C, V> {
    @Nullable final C lowerBound;
    @Nullable final C upperBound;
    TreeRow(R rowKey) {
      this(rowKeynullnull);
    }
    TreeRow(R rowKey, @Nullable C lowerBound, @Nullable C upperBound) {
      super(rowKey);
      this. = lowerBound;
      this. = upperBound;
      checkArgument(lowerBound == null || upperBound == null
          || compare(lowerBoundupperBound) <= 0);
    }
    @Override public Comparator<? super C> comparator() {
      return columnComparator();
    }
    int compare(Object aObject b) {
      // pretend we can compare anything
      @SuppressWarnings({"rawtypes""unchecked"})
      Comparator<Objectcmp = (Comparatorcomparator();
      return cmp.compare(ab);
    }
    boolean rangeContains(@Nullable Object o) {
      return o != null && ( == null || compare(o) <= 0)
          && ( == null || compare(o) > 0);
    }
    @Override public SortedMap<C, V> subMap(C fromKey, C toKey) {
          && rangeContains(checkNotNull(toKey)));
      return new TreeRow(fromKeytoKey);
    }
    @Override public SortedMap<C, V> headMap(C toKey) {
      return new TreeRow(toKey);
    }
    @Override public SortedMap<C, V> tailMap(C fromKey) {
      return new TreeRow(fromKey);
    }
    @Override public C firstKey() {
      SortedMap<C, V> backing = backingRowMap();
      if (backing == null) {
        throw new NoSuchElementException();
      }
      return backingRowMap().firstKey();
    }
    @Override public C lastKey() {
      SortedMap<C, V> backing = backingRowMap();
      if (backing == null) {
        throw new NoSuchElementException();
      }
      return backingRowMap().lastKey();
    }
    transient SortedMap<C, V> wholeRow;
    /*
     * If the row was previously empty, we check if there's a new row here every
     * time we're queried.
     */
    SortedMap<C, V> wholeRow() {
      if ( == null
          || (.isEmpty() && .containsKey())) {
         = (SortedMap<C, V>) .get();
      }
      return ;
    }
    @Override
    SortedMap<C, V> backingRowMap() {
      return (SortedMap<C, V>) super.backingRowMap();
    }
    @Override
    SortedMap<C, V> computeBackingRowMap() {
      SortedMap<C, V> map = wholeRow();
      if (map != null) {
        if ( != null) {
          map = map.tailMap();
        }
        if ( != null) {
          map = map.headMap();
        }
        return map;
      }
      return null;
    }
    @Override
    void maintainEmptyInvariant() {
      if (wholeRow() != null && .isEmpty()) {
        .remove();
         = null;
         = null;
      }
    }
    @Override public boolean containsKey(Object key) {
      return rangeContains(key) && super.containsKey(key);
    }
    @Override public V put(C key, V value) {
      return super.put(keyvalue);
    }
  }
  // rowKeySet() and rowMap() are defined here so they appear in the Javadoc.
  @Override public SortedSet<R> rowKeySet() {
    return super.rowKeySet();
  }
  @Override public SortedMap<R, Map<C, V>> rowMap() {
    return super.rowMap();
  }
  // Overriding so NullPointerTester test passes.
  @Override public boolean contains(
      @Nullable Object rowKey, @Nullable Object columnKey) {
    return super.contains(rowKeycolumnKey);
  }
  @Override public boolean containsColumn(@Nullable Object columnKey) {
    return super.containsColumn(columnKey);
  }
  @Override public boolean containsRow(@Nullable Object rowKey) {
    return super.containsRow(rowKey);
  }
  @Override public boolean containsValue(@Nullable Object value) {
    return super.containsValue(value);
  }
  @Override public V get(@Nullable Object rowKey, @Nullable Object columnKey) {
    return super.get(rowKeycolumnKey);
  }
  @Override public boolean equals(@Nullable Object obj) {
    return super.equals(obj);
  }
  @Override public V remove(
      @Nullable Object rowKey, @Nullable Object columnKey) {
    return super.remove(rowKeycolumnKey);
  }

  
Overridden column iterator to return columns values in globally sorted order.
    final Comparator<? super C> comparator = columnComparator();
    final Iterator<C> merged =
        Iterators.mergeSorted(Iterables.transform(.values(),
            new Function<Map<C, V>, Iterator<C>>() {
              @Override
              public Iterator<C> apply(Map<C, V> input) {
                return input.keySet().iterator();
              }
            }), comparator);
    return new AbstractIterator<C>() {
      C lastValue;
      @Override
      protected C computeNext() {
        while (merged.hasNext()) {
          C next = merged.next();
          boolean duplicate =
               != null && comparator.compare(next) == 0;
          // Keep looping till we find a non-duplicate value.
          if (!duplicate) {
             = next;
            return ;
          }
        }
         = null// clear reference to unused data
        return endOfData();
      }
    };
  }
  private static final long serialVersionUID = 0;
New to GrepCode? Check out our FAQ X