Coverage Summary for Class: ImmutableBiMap (com.google.common.collect)

Class Method, % Line, %
ImmutableBiMap 18.8% (3/16) 10.7% (3/28)
ImmutableBiMap$Builder 0% (0/10) 0% (0/30)
ImmutableBiMap$SerializedForm 0% (0/2) 0% (0/2)
Total 10.7% (3/28) 5% (3/60)


1 /* 2  * Copyright (C) 2008 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); 5  * you may not use this file except in compliance with the License. 6  * You may obtain a copy of the License at 7  * 8  * http://www.apache.org/licenses/LICENSE-2.0 9  * 10  * Unless required by applicable law or agreed to in writing, software 11  * distributed under the License is distributed on an "AS IS" BASIS, 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13  * See the License for the specific language governing permissions and 14  * limitations under the License. 15  */ 16  17 package com.google.common.collect; 18  19 import static com.google.common.base.Preconditions.checkState; 20 import static com.google.common.collect.CollectPreconditions.checkNonnegative; 21  22 import com.google.common.annotations.Beta; 23 import com.google.common.annotations.GwtCompatible; 24 import com.google.common.annotations.VisibleForTesting; 25 import com.google.errorprone.annotations.CanIgnoreReturnValue; 26 import com.google.errorprone.annotations.DoNotCall; 27 import java.util.Arrays; 28 import java.util.Comparator; 29 import java.util.Map; 30 import java.util.function.Function; 31 import java.util.stream.Collector; 32 import java.util.stream.Collectors; 33  34 /** 35  * A {@link BiMap} whose contents will never change, with many other important properties detailed 36  * at {@link ImmutableCollection}. 37  * 38  * @author Jared Levy 39  * @since 2.0 40  */ 41 @GwtCompatible(serializable = true, emulated = true) 42 public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<K, V> 43  implements BiMap<K, V> { 44  45  /** 46  * Returns a {@link Collector} that accumulates elements into an {@code ImmutableBiMap} whose keys 47  * and values are the result of applying the provided mapping functions to the input elements. 48  * Entries appear in the result {@code ImmutableBiMap} in encounter order. 49  * 50  * <p>If the mapped keys or values contain duplicates (according to {@link Object#equals(Object)}, 51  * an {@code IllegalArgumentException} is thrown when the collection operation is performed. (This 52  * differs from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, 53  * which throws an {@code IllegalStateException}.) 54  * 55  * @since 21.0 56  */ 57  public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap( 58  Function<? super T, ? extends K> keyFunction, 59  Function<? super T, ? extends V> valueFunction) { 60  return CollectCollectors.toImmutableBiMap(keyFunction, valueFunction); 61  } 62  63  /** 64  * Returns the empty bimap. 65  * 66  * <p><b>Performance note:</b> the instance returned is a singleton. 67  */ 68  // Casting to any type is safe because the set will never hold any elements. 69  @SuppressWarnings("unchecked") 70  public static <K, V> ImmutableBiMap<K, V> of() { 71  return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY; 72  } 73  74  /** Returns an immutable bimap containing a single entry. */ 75  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) { 76  return new SingletonImmutableBiMap<>(k1, v1); 77  } 78  79  /** 80  * Returns an immutable map containing the given entries, in order. 81  * 82  * @throws IllegalArgumentException if duplicate keys or values are added 83  */ 84  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) { 85  return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2)); 86  } 87  88  /** 89  * Returns an immutable map containing the given entries, in order. 90  * 91  * @throws IllegalArgumentException if duplicate keys or values are added 92  */ 93  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) { 94  return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3)); 95  } 96  97  /** 98  * Returns an immutable map containing the given entries, in order. 99  * 100  * @throws IllegalArgumentException if duplicate keys or values are added 101  */ 102  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) { 103  return RegularImmutableBiMap.fromEntries( 104  entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4)); 105  } 106  107  /** 108  * Returns an immutable map containing the given entries, in order. 109  * 110  * @throws IllegalArgumentException if duplicate keys or values are added 111  */ 112  public static <K, V> ImmutableBiMap<K, V> of( 113  K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) { 114  return RegularImmutableBiMap.fromEntries( 115  entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5)); 116  } 117  118  // looking for of() with > 5 entries? Use the builder instead. 119  120  /** 121  * Returns a new builder. The generated builder is equivalent to the builder created by the {@link 122  * Builder} constructor. 123  */ 124  public static <K, V> Builder<K, V> builder() { 125  return new Builder<>(); 126  } 127  128  /** 129  * Returns a new builder, expecting the specified number of entries to be added. 130  * 131  * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link 132  * Builder#build} is called, the builder is likely to perform better than an unsized {@link 133  * #builder()} would have. 134  * 135  * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to, 136  * but not exactly, the number of entries added to the builder. 137  * 138  * @since 23.1 139  */ 140  @Beta 141  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) { 142  checkNonnegative(expectedSize, "expectedSize"); 143  return new Builder<>(expectedSize); 144  } 145  146  /** 147  * A builder for creating immutable bimap instances, especially {@code public static final} bimaps 148  * ("constant bimaps"). Example: 149  * 150  * <pre>{@code 151  * static final ImmutableBiMap<String, Integer> WORD_TO_INT = 152  * new ImmutableBiMap.Builder<String, Integer>() 153  * .put("one", 1) 154  * .put("two", 2) 155  * .put("three", 3) 156  * .build(); 157  * }</pre> 158  * 159  * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more 160  * convenient. 161  * 162  * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order 163  * they were inserted into the builder. For example, in the above example, {@code 164  * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1, 165  * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you 166  * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes 167  * this builder to sort entries by value. 168  * 169  * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build 170  * multiple bimaps in series. Each bimap is a superset of the bimaps created before it. 171  * 172  * @since 2.0 173  */ 174  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> { 175  176  /** 177  * Creates a new builder. The returned builder is equivalent to the builder generated by {@link 178  * ImmutableBiMap#builder}. 179  */ 180  public Builder() {} 181  182  Builder(int size) { 183  super(size); 184  } 185  186  /** 187  * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are 188  * not allowed, and will cause {@link #build} to fail. 189  */ 190  @CanIgnoreReturnValue 191  @Override 192  public Builder<K, V> put(K key, V value) { 193  super.put(key, value); 194  return this; 195  } 196  197  /** 198  * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will 199  * cause {@link #build} to fail. 200  * 201  * @since 19.0 202  */ 203  @CanIgnoreReturnValue 204  @Override 205  public Builder<K, V> put(Entry<? extends K, ? extends V> entry) { 206  super.put(entry); 207  return this; 208  } 209  210  /** 211  * Associates all of the given map's keys and values in the built bimap. Duplicate keys or 212  * values are not allowed, and will cause {@link #build} to fail. 213  * 214  * @throws NullPointerException if any key or value in {@code map} is null 215  */ 216  @CanIgnoreReturnValue 217  @Override 218  public Builder<K, V> putAll(Map<? extends K, ? extends V> map) { 219  super.putAll(map); 220  return this; 221  } 222  223  /** 224  * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed, 225  * and will cause {@link #build} to fail. 226  * 227  * @throws NullPointerException if any key, value, or entry is null 228  * @since 19.0 229  */ 230  @CanIgnoreReturnValue 231  @Beta 232  @Override 233  public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) { 234  super.putAll(entries); 235  return this; 236  } 237  238  /** 239  * Configures this {@code Builder} to order entries by value according to the specified 240  * comparator. 241  * 242  * <p>The sort order is stable, that is, if two entries have values that compare as equivalent, 243  * the entry that was inserted first will be first in the built map's iteration order. 244  * 245  * @throws IllegalStateException if this method was already called 246  * @since 19.0 247  */ 248  @CanIgnoreReturnValue 249  @Beta 250  @Override 251  public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) { 252  super.orderEntriesByValue(valueComparator); 253  return this; 254  } 255  256  @Override 257  @CanIgnoreReturnValue 258  Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) { 259  super.combine(builder); 260  return this; 261  } 262  263  /** 264  * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the 265  * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue} 266  * was called, in which case entries are sorted by value. 267  * 268  * @throws IllegalArgumentException if duplicate keys or values were added 269  */ 270  @Override 271  public ImmutableBiMap<K, V> build() { 272  switch (size) { 273  case 0: 274  return of(); 275  case 1: 276  return of(entries[0].getKey(), entries[0].getValue()); 277  default: 278  /* 279  * If entries is full, or if hash flooding is detected, then this implementation may end 280  * up using the entries array directly and writing over the entry objects with 281  * non-terminal entries, but this is safe; if this Builder is used further, it will grow 282  * the entries array (so it can't affect the original array), and future build() calls 283  * will always copy any entry objects that cannot be safely reused. 284  */ 285  if (valueComparator != null) { 286  if (entriesUsed) { 287  entries = Arrays.copyOf(entries, size); 288  } 289  Arrays.sort( 290  entries, 291  0, 292  size, 293  Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction())); 294  } 295  entriesUsed = true; 296  return RegularImmutableBiMap.fromEntryArray(size, entries); 297  } 298  } 299  300  @Override 301  @VisibleForTesting 302  ImmutableBiMap<K, V> buildJdkBacked() { 303  checkState( 304  valueComparator == null, 305  "buildJdkBacked is for tests only, doesn't support orderEntriesByValue"); 306  switch (size) { 307  case 0: 308  return of(); 309  case 1: 310  return of(entries[0].getKey(), entries[0].getValue()); 311  default: 312  entriesUsed = true; 313  return RegularImmutableBiMap.fromEntryArray(size, entries); 314  } 315  } 316  } 317  318  /** 319  * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow 320  * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose 321  * comparator is not <i>consistent with equals</i>), the results of this method are undefined. 322  * 323  * <p>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet} 324  * of the original map. 325  * 326  * <p>Despite the method name, this method attempts to avoid actually copying the data when it is 327  * safe to do so. The exact circumstances under which a copy will or will not be performed are 328  * undocumented and subject to change. 329  * 330  * @throws IllegalArgumentException if two keys have the same value or two values have the same 331  * key 332  * @throws NullPointerException if any key or value in {@code map} is null 333  */ 334  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) { 335  if (map instanceof ImmutableBiMap) { 336  @SuppressWarnings("unchecked") // safe since map is not writable 337  ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map; 338  // TODO(lowasser): if we need to make a copy of a BiMap because the 339  // forward map is a view, don't make a copy of the non-view delegate map 340  if (!bimap.isPartialView()) { 341  return bimap; 342  } 343  } 344  return copyOf(map.entrySet()); 345  } 346  347  /** 348  * Returns an immutable bimap containing the given entries. The returned bimap iterates over 349  * entries in the same order as the original iterable. 350  * 351  * @throws IllegalArgumentException if two keys have the same value or two values have the same 352  * key 353  * @throws NullPointerException if any key, value, or entry is null 354  * @since 19.0 355  */ 356  @Beta 357  public static <K, V> ImmutableBiMap<K, V> copyOf( 358  Iterable<? extends Entry<? extends K, ? extends V>> entries) { 359  @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant 360  Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY); 361  switch (entryArray.length) { 362  case 0: 363  return of(); 364  case 1: 365  Entry<K, V> entry = entryArray[0]; 366  return of(entry.getKey(), entry.getValue()); 367  default: 368  /* 369  * The current implementation will end up using entryArray directly, though it will write 370  * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray. 371  */ 372  return RegularImmutableBiMap.fromEntries(entryArray); 373  } 374  } 375  376  ImmutableBiMap() {} 377  378  /** 379  * {@inheritDoc} 380  * 381  * <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}. 382  */ 383  @Override 384  public abstract ImmutableBiMap<V, K> inverse(); 385  386  /** 387  * Returns an immutable set of the values in this map, in the same order they appear in {@link 388  * #entrySet}. 389  */ 390  @Override 391  public ImmutableSet<V> values() { 392  return inverse().keySet(); 393  } 394  395  @Override 396  final ImmutableSet<V> createValues() { 397  throw new AssertionError("should never be called"); 398  } 399  400  /** 401  * Guaranteed to throw an exception and leave the bimap unmodified. 402  * 403  * @throws UnsupportedOperationException always 404  * @deprecated Unsupported operation. 405  */ 406  @CanIgnoreReturnValue 407  @Deprecated 408  @Override 409  @DoNotCall("Always throws UnsupportedOperationException") 410  public final V forcePut(K key, V value) { 411  throw new UnsupportedOperationException(); 412  } 413  414  /** 415  * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are 416  * reconstructed using public factory methods. This ensures that the implementation types remain 417  * as implementation details. 418  * 419  * <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the 420  * bimap and its inverse in sync during serialization, the way AbstractBiMap does. 421  */ 422  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> { 423  SerializedForm(ImmutableBiMap<K, V> bimap) { 424  super(bimap); 425  } 426  427  @Override 428  Builder<K, V> makeBuilder(int size) { 429  return new Builder<>(size); 430  } 431  432  private static final long serialVersionUID = 0; 433  } 434  435  @Override 436  Object writeReplace() { 437  return new SerializedForm<>(this); 438  } 439 }