001/* 002 * Copyright (C) 2009 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.checkNotNull; 020 021import com.google.common.annotations.Beta; 022import com.google.common.annotations.GwtCompatible; 023import com.google.common.base.MoreObjects; 024import com.google.common.collect.Tables.AbstractCell; 025import com.google.errorprone.annotations.CanIgnoreReturnValue; 026import java.io.Serializable; 027import java.util.ArrayList; 028import java.util.Comparator; 029import java.util.Iterator; 030import java.util.List; 031import java.util.Map; 032import java.util.Spliterator; 033import java.util.function.BinaryOperator; 034import java.util.function.Function; 035import java.util.stream.Collector; 036import org.checkerframework.checker.nullness.compatqual.NullableDecl; 037 038/** 039 * A {@link Table} whose contents will never change, with many other important properties detailed 040 * at {@link ImmutableCollection}. 041 * 042 * <p>See the Guava User Guide article on <a href= 043 * "https://github.com/google/guava/wiki/ImmutableCollectionsExplained"> immutable collections</a>. 044 * 045 * @author Gregory Kick 046 * @since 11.0 047 */ 048@GwtCompatible 049public abstract class ImmutableTable<R, C, V> extends AbstractTable<R, C, V> 050 implements Serializable { 051 052 /** 053 * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each 054 * input element is mapped to one cell in the returned table, with the rows, columns, and values 055 * generated by applying the specified functions. 056 * 057 * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time 058 * if the row, column, or value functions return null on any input. 059 * 060 * @since 21.0 061 */ 062 @Beta 063 public static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable( 064 Function<? super T, ? extends R> rowFunction, 065 Function<? super T, ? extends C> columnFunction, 066 Function<? super T, ? extends V> valueFunction) { 067 checkNotNull(rowFunction); 068 checkNotNull(columnFunction); 069 checkNotNull(valueFunction); 070 return Collector.of( 071 () -> new ImmutableTable.Builder<R, C, V>(), 072 (builder, t) -> 073 builder.put(rowFunction.apply(t), columnFunction.apply(t), valueFunction.apply(t)), 074 (b1, b2) -> b1.combine(b2), 075 b -> b.build()); 076 } 077 078 /** 079 * Returns a {@code Collector} that accumulates elements into an {@code ImmutableTable}. Each 080 * input element is mapped to one cell in the returned table, with the rows, columns, and values 081 * generated by applying the specified functions. If multiple inputs are mapped to the same row 082 * and column pair, they will be combined with the specified merging function in encounter order. 083 * 084 * <p>The returned {@code Collector} will throw a {@code NullPointerException} at collection time 085 * if the row, column, value, or merging functions return null on any input. 086 * 087 * @since 21.0 088 */ 089 public static <T, R, C, V> Collector<T, ?, ImmutableTable<R, C, V>> toImmutableTable( 090 Function<? super T, ? extends R> rowFunction, 091 Function<? super T, ? extends C> columnFunction, 092 Function<? super T, ? extends V> valueFunction, 093 BinaryOperator<V> mergeFunction) { 094 095 checkNotNull(rowFunction); 096 checkNotNull(columnFunction); 097 checkNotNull(valueFunction); 098 checkNotNull(mergeFunction); 099 100 /* 101 * No mutable Table exactly matches the insertion order behavior of ImmutableTable.Builder, but 102 * the Builder can't efficiently support merging of duplicate values. Getting around this 103 * requires some work. 104 */ 105 106 return Collector.of( 107 () -> new CollectorState<R, C, V>() 108 /* GWT isn't currently playing nicely with constructor references? */ , 109 (state, input) -> 110 state.put( 111 rowFunction.apply(input), 112 columnFunction.apply(input), 113 valueFunction.apply(input), 114 mergeFunction), 115 (s1, s2) -> s1.combine(s2, mergeFunction), 116 state -> state.toTable()); 117 } 118 119 private static final class CollectorState<R, C, V> { 120 final List<MutableCell<R, C, V>> insertionOrder = new ArrayList<>(); 121 final Table<R, C, MutableCell<R, C, V>> table = HashBasedTable.create(); 122 123 void put(R row, C column, V value, BinaryOperator<V> merger) { 124 MutableCell<R, C, V> oldCell = table.get(row, column); 125 if (oldCell == null) { 126 MutableCell<R, C, V> cell = new MutableCell<>(row, column, value); 127 insertionOrder.add(cell); 128 table.put(row, column, cell); 129 } else { 130 oldCell.merge(value, merger); 131 } 132 } 133 134 CollectorState<R, C, V> combine(CollectorState<R, C, V> other, BinaryOperator<V> merger) { 135 for (MutableCell<R, C, V> cell : other.insertionOrder) { 136 put(cell.getRowKey(), cell.getColumnKey(), cell.getValue(), merger); 137 } 138 return this; 139 } 140 141 ImmutableTable<R, C, V> toTable() { 142 return copyOf(insertionOrder); 143 } 144 } 145 146 private static final class MutableCell<R, C, V> extends AbstractCell<R, C, V> { 147 private final R row; 148 private final C column; 149 private V value; 150 151 MutableCell(R row, C column, V value) { 152 this.row = checkNotNull(row); 153 this.column = checkNotNull(column); 154 this.value = checkNotNull(value); 155 } 156 157 @Override 158 public R getRowKey() { 159 return row; 160 } 161 162 @Override 163 public C getColumnKey() { 164 return column; 165 } 166 167 @Override 168 public V getValue() { 169 return value; 170 } 171 172 void merge(V value, BinaryOperator<V> mergeFunction) { 173 checkNotNull(value); 174 this.value = checkNotNull(mergeFunction.apply(this.value, value)); 175 } 176 } 177 178 /** Returns an empty immutable table. */ 179 @SuppressWarnings("unchecked") 180 public static <R, C, V> ImmutableTable<R, C, V> of() { 181 return (ImmutableTable<R, C, V>) SparseImmutableTable.EMPTY; 182 } 183 184 /** Returns an immutable table containing a single cell. */ 185 public static <R, C, V> ImmutableTable<R, C, V> of(R rowKey, C columnKey, V value) { 186 return new SingletonImmutableTable<>(rowKey, columnKey, value); 187 } 188 189 /** 190 * Returns an immutable copy of the provided table. 191 * 192 * <p>The {@link Table#cellSet()} iteration order of the provided table determines the iteration 193 * ordering of all views in the returned table. Note that some views of the original table and the 194 * copied table may have different iteration orders. For more control over the ordering, create a 195 * {@link Builder} and call {@link Builder#orderRowsBy}, {@link Builder#orderColumnsBy}, and 196 * {@link Builder#putAll} 197 * 198 * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 199 * safe to do so. The exact circumstances under which a copy will or will not be performed are 200 * undocumented and subject to change. 201 */ 202 public static <R, C, V> ImmutableTable<R, C, V> copyOf( 203 Table<? extends R, ? extends C, ? extends V> table) { 204 if (table instanceof ImmutableTable) { 205 @SuppressWarnings("unchecked") 206 ImmutableTable<R, C, V> parameterizedTable = (ImmutableTable<R, C, V>) table; 207 return parameterizedTable; 208 } else { 209 return copyOf(table.cellSet()); 210 } 211 } 212 213 private static <R, C, V> ImmutableTable<R, C, V> copyOf( 214 Iterable<? extends Cell<? extends R, ? extends C, ? extends V>> cells) { 215 ImmutableTable.Builder<R, C, V> builder = ImmutableTable.builder(); 216 for (Cell<? extends R, ? extends C, ? extends V> cell : cells) { 217 builder.put(cell); 218 } 219 return builder.build(); 220 } 221 222 /** 223 * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 224 * Builder#Builder() ImmutableTable.Builder()} constructor. 225 */ 226 public static <R, C, V> Builder<R, C, V> builder() { 227 return new Builder<>(); 228 } 229 230 /** 231 * Verifies that {@code rowKey}, {@code columnKey} and {@code value} are non-null, and returns a 232 * new entry with those values. 233 */ 234 static <R, C, V> Cell<R, C, V> cellOf(R rowKey, C columnKey, V value) { 235 return Tables.immutableCell(checkNotNull(rowKey), checkNotNull(columnKey), checkNotNull(value)); 236 } 237 238 /** 239 * A builder for creating immutable table instances, especially {@code public static final} tables 240 * ("constant tables"). Example: 241 * 242 * <pre>{@code 243 * static final ImmutableTable<Integer, Character, String> SPREADSHEET = 244 * new ImmutableTable.Builder<Integer, Character, String>() 245 * .put(1, 'A', "foo") 246 * .put(1, 'B', "bar") 247 * .put(2, 'A', "baz") 248 * .build(); 249 * }</pre> 250 * 251 * <p>By default, the order in which cells are added to the builder determines the iteration 252 * ordering of all views in the returned table, with {@link #putAll} following the {@link 253 * Table#cellSet()} iteration order. However, if {@link #orderRowsBy} or {@link #orderColumnsBy} 254 * is called, the views are sorted by the supplied comparators. 255 * 256 * <p>For empty or single-cell immutable tables, {@link #of()} and {@link #of(Object, Object, 257 * Object)} are even more convenient. 258 * 259 * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build 260 * multiple tables in series. Each table is a superset of the tables created before it. 261 * 262 * @since 11.0 263 */ 264 public static final class Builder<R, C, V> { 265 private final List<Cell<R, C, V>> cells = Lists.newArrayList(); 266 private Comparator<? super R> rowComparator; 267 private Comparator<? super C> columnComparator; 268 269 /** 270 * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 271 * ImmutableTable#builder}. 272 */ 273 public Builder() {} 274 275 /** Specifies the ordering of the generated table's rows. */ 276 @CanIgnoreReturnValue 277 public Builder<R, C, V> orderRowsBy(Comparator<? super R> rowComparator) { 278 this.rowComparator = checkNotNull(rowComparator); 279 return this; 280 } 281 282 /** Specifies the ordering of the generated table's columns. */ 283 @CanIgnoreReturnValue 284 public Builder<R, C, V> orderColumnsBy(Comparator<? super C> columnComparator) { 285 this.columnComparator = checkNotNull(columnComparator); 286 return this; 287 } 288 289 /** 290 * Associates the ({@code rowKey}, {@code columnKey}) pair with {@code value} in the built 291 * table. Duplicate key pairs are not allowed and will cause {@link #build} to fail. 292 */ 293 @CanIgnoreReturnValue 294 public Builder<R, C, V> put(R rowKey, C columnKey, V value) { 295 cells.add(cellOf(rowKey, columnKey, value)); 296 return this; 297 } 298 299 /** 300 * Adds the given {@code cell} to the table, making it immutable if necessary. Duplicate key 301 * pairs are not allowed and will cause {@link #build} to fail. 302 */ 303 @CanIgnoreReturnValue 304 public Builder<R, C, V> put(Cell<? extends R, ? extends C, ? extends V> cell) { 305 if (cell instanceof Tables.ImmutableCell) { 306 checkNotNull(cell.getRowKey()); 307 checkNotNull(cell.getColumnKey()); 308 checkNotNull(cell.getValue()); 309 @SuppressWarnings("unchecked") // all supported methods are covariant 310 Cell<R, C, V> immutableCell = (Cell<R, C, V>) cell; 311 cells.add(immutableCell); 312 } else { 313 put(cell.getRowKey(), cell.getColumnKey(), cell.getValue()); 314 } 315 return this; 316 } 317 318 /** 319 * Associates all of the given table's keys and values in the built table. Duplicate row key 320 * column key pairs are not allowed, and will cause {@link #build} to fail. 321 * 322 * @throws NullPointerException if any key or value in {@code table} is null 323 */ 324 @CanIgnoreReturnValue 325 public Builder<R, C, V> putAll(Table<? extends R, ? extends C, ? extends V> table) { 326 for (Cell<? extends R, ? extends C, ? extends V> cell : table.cellSet()) { 327 put(cell); 328 } 329 return this; 330 } 331 332 Builder<R, C, V> combine(Builder<R, C, V> other) { 333 this.cells.addAll(other.cells); 334 return this; 335 } 336 337 /** 338 * Returns a newly-created immutable table. 339 * 340 * @throws IllegalArgumentException if duplicate key pairs were added 341 */ 342 public ImmutableTable<R, C, V> build() { 343 int size = cells.size(); 344 switch (size) { 345 case 0: 346 return of(); 347 case 1: 348 return new SingletonImmutableTable<>(Iterables.getOnlyElement(cells)); 349 default: 350 return RegularImmutableTable.forCells(cells, rowComparator, columnComparator); 351 } 352 } 353 } 354 355 ImmutableTable() {} 356 357 @Override 358 public ImmutableSet<Cell<R, C, V>> cellSet() { 359 return (ImmutableSet<Cell<R, C, V>>) super.cellSet(); 360 } 361 362 @Override 363 abstract ImmutableSet<Cell<R, C, V>> createCellSet(); 364 365 @Override 366 final UnmodifiableIterator<Cell<R, C, V>> cellIterator() { 367 throw new AssertionError("should never be called"); 368 } 369 370 @Override 371 final Spliterator<Cell<R, C, V>> cellSpliterator() { 372 throw new AssertionError("should never be called"); 373 } 374 375 @Override 376 public ImmutableCollection<V> values() { 377 return (ImmutableCollection<V>) super.values(); 378 } 379 380 @Override 381 abstract ImmutableCollection<V> createValues(); 382 383 @Override 384 final Iterator<V> valuesIterator() { 385 throw new AssertionError("should never be called"); 386 } 387 388 /** 389 * {@inheritDoc} 390 * 391 * @throws NullPointerException if {@code columnKey} is {@code null} 392 */ 393 @Override 394 public ImmutableMap<R, V> column(C columnKey) { 395 checkNotNull(columnKey); 396 return MoreObjects.firstNonNull( 397 (ImmutableMap<R, V>) columnMap().get(columnKey), ImmutableMap.<R, V>of()); 398 } 399 400 @Override 401 public ImmutableSet<C> columnKeySet() { 402 return columnMap().keySet(); 403 } 404 405 /** 406 * {@inheritDoc} 407 * 408 * <p>The value {@code Map<R, V>} instances in the returned map are {@link ImmutableMap} instances 409 * as well. 410 */ 411 @Override 412 public abstract ImmutableMap<C, Map<R, V>> columnMap(); 413 414 /** 415 * {@inheritDoc} 416 * 417 * @throws NullPointerException if {@code rowKey} is {@code null} 418 */ 419 @Override 420 public ImmutableMap<C, V> row(R rowKey) { 421 checkNotNull(rowKey); 422 return MoreObjects.firstNonNull( 423 (ImmutableMap<C, V>) rowMap().get(rowKey), ImmutableMap.<C, V>of()); 424 } 425 426 @Override 427 public ImmutableSet<R> rowKeySet() { 428 return rowMap().keySet(); 429 } 430 431 /** 432 * {@inheritDoc} 433 * 434 * <p>The value {@code Map<C, V>} instances in the returned map are {@link ImmutableMap} instances 435 * as well. 436 */ 437 @Override 438 public abstract ImmutableMap<R, Map<C, V>> rowMap(); 439 440 @Override 441 public boolean contains(@NullableDecl Object rowKey, @NullableDecl Object columnKey) { 442 return get(rowKey, columnKey) != null; 443 } 444 445 @Override 446 public boolean containsValue(@NullableDecl Object value) { 447 return values().contains(value); 448 } 449 450 /** 451 * Guaranteed to throw an exception and leave the table unmodified. 452 * 453 * @throws UnsupportedOperationException always 454 * @deprecated Unsupported operation. 455 */ 456 @Deprecated 457 @Override 458 public final void clear() { 459 throw new UnsupportedOperationException(); 460 } 461 462 /** 463 * Guaranteed to throw an exception and leave the table unmodified. 464 * 465 * @throws UnsupportedOperationException always 466 * @deprecated Unsupported operation. 467 */ 468 @CanIgnoreReturnValue 469 @Deprecated 470 @Override 471 public final V put(R rowKey, C columnKey, V value) { 472 throw new UnsupportedOperationException(); 473 } 474 475 /** 476 * Guaranteed to throw an exception and leave the table unmodified. 477 * 478 * @throws UnsupportedOperationException always 479 * @deprecated Unsupported operation. 480 */ 481 @Deprecated 482 @Override 483 public final void putAll(Table<? extends R, ? extends C, ? extends V> table) { 484 throw new UnsupportedOperationException(); 485 } 486 487 /** 488 * Guaranteed to throw an exception and leave the table unmodified. 489 * 490 * @throws UnsupportedOperationException always 491 * @deprecated Unsupported operation. 492 */ 493 @CanIgnoreReturnValue 494 @Deprecated 495 @Override 496 public final V remove(Object rowKey, Object columnKey) { 497 throw new UnsupportedOperationException(); 498 } 499 500 /** Creates the common serialized form for this table. */ 501 abstract SerializedForm createSerializedForm(); 502 503 /** 504 * Serialized type for all ImmutableTable instances. It captures the logical contents and 505 * preserves iteration order of all views. 506 */ 507 static final class SerializedForm implements Serializable { 508 private final Object[] rowKeys; 509 private final Object[] columnKeys; 510 511 private final Object[] cellValues; 512 private final int[] cellRowIndices; 513 private final int[] cellColumnIndices; 514 515 private SerializedForm( 516 Object[] rowKeys, 517 Object[] columnKeys, 518 Object[] cellValues, 519 int[] cellRowIndices, 520 int[] cellColumnIndices) { 521 this.rowKeys = rowKeys; 522 this.columnKeys = columnKeys; 523 this.cellValues = cellValues; 524 this.cellRowIndices = cellRowIndices; 525 this.cellColumnIndices = cellColumnIndices; 526 } 527 528 static SerializedForm create( 529 ImmutableTable<?, ?, ?> table, int[] cellRowIndices, int[] cellColumnIndices) { 530 return new SerializedForm( 531 table.rowKeySet().toArray(), 532 table.columnKeySet().toArray(), 533 table.values().toArray(), 534 cellRowIndices, 535 cellColumnIndices); 536 } 537 538 Object readResolve() { 539 if (cellValues.length == 0) { 540 return of(); 541 } 542 if (cellValues.length == 1) { 543 return of(rowKeys[0], columnKeys[0], cellValues[0]); 544 } 545 ImmutableList.Builder<Cell<Object, Object, Object>> cellListBuilder = 546 new ImmutableList.Builder<>(cellValues.length); 547 for (int i = 0; i < cellValues.length; i++) { 548 cellListBuilder.add( 549 cellOf(rowKeys[cellRowIndices[i]], columnKeys[cellColumnIndices[i]], cellValues[i])); 550 } 551 return RegularImmutableTable.forOrderedComponents( 552 cellListBuilder.build(), ImmutableSet.copyOf(rowKeys), ImmutableSet.copyOf(columnKeys)); 553 } 554 555 private static final long serialVersionUID = 0; 556 } 557 558 final Object writeReplace() { 559 return createSerializedForm(); 560 } 561}