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.checkState;
020import static com.google.common.collect.CollectPreconditions.checkNonnegative;
021
022import com.google.common.annotations.Beta;
023import com.google.common.annotations.GwtCompatible;
024import com.google.common.annotations.VisibleForTesting;
025import com.google.errorprone.annotations.CanIgnoreReturnValue;
026import java.util.Arrays;
027import java.util.Comparator;
028import java.util.Map;
029import java.util.function.Function;
030import java.util.stream.Collector;
031import java.util.stream.Collectors;
032
033/**
034 * A {@link BiMap} whose contents will never change, with many other important properties detailed
035 * at {@link ImmutableCollection}.
036 *
037 * @author Jared Levy
038 * @since 2.0
039 */
040@GwtCompatible(serializable = true, emulated = true)
041public abstract class ImmutableBiMap<K, V> extends ImmutableBiMapFauxverideShim<K, V>
042    implements BiMap<K, V> {
043
044  /**
045   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableBiMap} whose keys
046   * and values are the result of applying the provided mapping functions to the input elements.
047   * Entries appear in the result {@code ImmutableBiMap} in encounter order.
048   *
049   * <p>If the mapped keys or values contain duplicates (according to {@link Object#equals(Object)},
050   * an {@code IllegalArgumentException} is thrown when the collection operation is performed. (This
051   * differs from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)},
052   * which throws an {@code IllegalStateException}.)
053   *
054   * @since 21.0
055   */
056  public static <T, K, V> Collector<T, ?, ImmutableBiMap<K, V>> toImmutableBiMap(
057      Function<? super T, ? extends K> keyFunction,
058      Function<? super T, ? extends V> valueFunction) {
059    return CollectCollectors.toImmutableBiMap(keyFunction, valueFunction);
060  }
061
062  /** Returns the empty bimap. */
063  // Casting to any type is safe because the set will never hold any elements.
064  @SuppressWarnings("unchecked")
065  public static <K, V> ImmutableBiMap<K, V> of() {
066    return (ImmutableBiMap<K, V>) RegularImmutableBiMap.EMPTY;
067  }
068
069  /** Returns an immutable bimap containing a single entry. */
070  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1) {
071    return new SingletonImmutableBiMap<>(k1, v1);
072  }
073
074  /**
075   * Returns an immutable map containing the given entries, in order.
076   *
077   * @throws IllegalArgumentException if duplicate keys or values are added
078   */
079  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2) {
080    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2));
081  }
082
083  /**
084   * Returns an immutable map containing the given entries, in order.
085   *
086   * @throws IllegalArgumentException if duplicate keys or values are added
087   */
088  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3) {
089    return RegularImmutableBiMap.fromEntries(entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3));
090  }
091
092  /**
093   * Returns an immutable map containing the given entries, in order.
094   *
095   * @throws IllegalArgumentException if duplicate keys or values are added
096   */
097  public static <K, V> ImmutableBiMap<K, V> of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4) {
098    return RegularImmutableBiMap.fromEntries(
099        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4));
100  }
101
102  /**
103   * Returns an immutable map containing the given entries, in order.
104   *
105   * @throws IllegalArgumentException if duplicate keys or values are added
106   */
107  public static <K, V> ImmutableBiMap<K, V> of(
108      K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5) {
109    return RegularImmutableBiMap.fromEntries(
110        entryOf(k1, v1), entryOf(k2, v2), entryOf(k3, v3), entryOf(k4, v4), entryOf(k5, v5));
111  }
112
113  // looking for of() with > 5 entries? Use the builder instead.
114
115  /**
116   * Returns a new builder. The generated builder is equivalent to the builder created by the {@link
117   * Builder} constructor.
118   */
119  public static <K, V> Builder<K, V> builder() {
120    return new Builder<>();
121  }
122
123  /**
124   * Returns a new builder, expecting the specified number of entries to be added.
125   *
126   * <p>If {@code expectedSize} is exactly the number of entries added to the builder before {@link
127   * Builder#build} is called, the builder is likely to perform better than an unsized {@link
128   * #builder()} would have.
129   *
130   * <p>It is not specified if any performance benefits apply if {@code expectedSize} is close to,
131   * but not exactly, the number of entries added to the builder.
132   *
133   * @since 23.1
134   */
135  @Beta
136  public static <K, V> Builder<K, V> builderWithExpectedSize(int expectedSize) {
137    checkNonnegative(expectedSize, "expectedSize");
138    return new Builder<>(expectedSize);
139  }
140
141  /**
142   * A builder for creating immutable bimap instances, especially {@code public static final} bimaps
143   * ("constant bimaps"). Example:
144   *
145   * <pre>{@code
146   * static final ImmutableBiMap<String, Integer> WORD_TO_INT =
147   *     new ImmutableBiMap.Builder<String, Integer>()
148   *         .put("one", 1)
149   *         .put("two", 2)
150   *         .put("three", 3)
151   *         .build();
152   * }</pre>
153   *
154   * <p>For <i>small</i> immutable bimaps, the {@code ImmutableBiMap.of()} methods are even more
155   * convenient.
156   *
157   * <p>By default, a {@code Builder} will generate bimaps that iterate over entries in the order
158   * they were inserted into the builder. For example, in the above example, {@code
159   * WORD_TO_INT.entrySet()} is guaranteed to iterate over the entries in the order {@code "one"=1,
160   * "two"=2, "three"=3}, and {@code keySet()} and {@code values()} respect the same order. If you
161   * want a different order, consider using {@link #orderEntriesByValue(Comparator)}, which changes
162   * this builder to sort entries by value.
163   *
164   * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build
165   * multiple bimaps in series. Each bimap is a superset of the bimaps created before it.
166   *
167   * @since 2.0
168   */
169  public static final class Builder<K, V> extends ImmutableMap.Builder<K, V> {
170
171    /**
172     * Creates a new builder. The returned builder is equivalent to the builder generated by {@link
173     * ImmutableBiMap#builder}.
174     */
175    public Builder() {}
176
177    Builder(int size) {
178      super(size);
179    }
180
181    /**
182     * Associates {@code key} with {@code value} in the built bimap. Duplicate keys or values are
183     * not allowed, and will cause {@link #build} to fail.
184     */
185    @CanIgnoreReturnValue
186    @Override
187    public Builder<K, V> put(K key, V value) {
188      super.put(key, value);
189      return this;
190    }
191
192    /**
193     * Adds the given {@code entry} to the bimap. Duplicate keys or values are not allowed, and will
194     * cause {@link #build} to fail.
195     *
196     * @since 19.0
197     */
198    @CanIgnoreReturnValue
199    @Override
200    public Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
201      super.put(entry);
202      return this;
203    }
204
205    /**
206     * Associates all of the given map's keys and values in the built bimap. Duplicate keys or
207     * values are not allowed, and will cause {@link #build} to fail.
208     *
209     * @throws NullPointerException if any key or value in {@code map} is null
210     */
211    @CanIgnoreReturnValue
212    @Override
213    public Builder<K, V> putAll(Map<? extends K, ? extends V> map) {
214      super.putAll(map);
215      return this;
216    }
217
218    /**
219     * Adds all of the given entries to the built bimap. Duplicate keys or values are not allowed,
220     * and will cause {@link #build} to fail.
221     *
222     * @throws NullPointerException if any key, value, or entry is null
223     * @since 19.0
224     */
225    @CanIgnoreReturnValue
226    @Beta
227    @Override
228    public Builder<K, V> putAll(Iterable<? extends Entry<? extends K, ? extends V>> entries) {
229      super.putAll(entries);
230      return this;
231    }
232
233    /**
234     * Configures this {@code Builder} to order entries by value according to the specified
235     * comparator.
236     *
237     * <p>The sort order is stable, that is, if two entries have values that compare as equivalent,
238     * the entry that was inserted first will be first in the built map's iteration order.
239     *
240     * @throws IllegalStateException if this method was already called
241     * @since 19.0
242     */
243    @CanIgnoreReturnValue
244    @Beta
245    @Override
246    public Builder<K, V> orderEntriesByValue(Comparator<? super V> valueComparator) {
247      super.orderEntriesByValue(valueComparator);
248      return this;
249    }
250
251    @Override
252    @CanIgnoreReturnValue
253    Builder<K, V> combine(ImmutableMap.Builder<K, V> builder) {
254      super.combine(builder);
255      return this;
256    }
257
258    /**
259     * Returns a newly-created immutable bimap. The iteration order of the returned bimap is the
260     * order in which entries were inserted into the builder, unless {@link #orderEntriesByValue}
261     * was called, in which case entries are sorted by value.
262     *
263     * @throws IllegalArgumentException if duplicate keys or values were added
264     */
265    @Override
266    public ImmutableBiMap<K, V> build() {
267      switch (size) {
268        case 0:
269          return of();
270        case 1:
271          return of(entries[0].getKey(), entries[0].getValue());
272        default:
273          /*
274           * If entries is full, or if hash flooding is detected, then this implementation may end
275           * up using the entries array directly and writing over the entry objects with
276           * non-terminal entries, but this is safe; if this Builder is used further, it will grow
277           * the entries array (so it can't affect the original array), and future build() calls
278           * will always copy any entry objects that cannot be safely reused.
279           */
280          if (valueComparator != null) {
281            if (entriesUsed) {
282              entries = Arrays.copyOf(entries, size);
283            }
284            Arrays.sort(
285                entries,
286                0,
287                size,
288                Ordering.from(valueComparator).onResultOf(Maps.<V>valueFunction()));
289          }
290          entriesUsed = true;
291          return RegularImmutableBiMap.fromEntryArray(size, entries);
292      }
293    }
294
295    @Override
296    @VisibleForTesting
297    ImmutableBiMap<K, V> buildJdkBacked() {
298      checkState(
299          valueComparator == null,
300          "buildJdkBacked is for tests only, doesn't support orderEntriesByValue");
301      switch (size) {
302        case 0:
303          return of();
304        case 1:
305          return of(entries[0].getKey(), entries[0].getValue());
306        default:
307          entriesUsed = true;
308          return RegularImmutableBiMap.fromEntryArray(size, entries);
309      }
310    }
311  }
312
313  /**
314   * Returns an immutable bimap containing the same entries as {@code map}. If {@code map} somehow
315   * contains entries with duplicate keys (for example, if it is a {@code SortedMap} whose
316   * comparator is not <i>consistent with equals</i>), the results of this method are undefined.
317   *
318   * <p>The returned {@code BiMap} iterates over entries in the same order as the {@code entrySet}
319   * of the original map.
320   *
321   * <p>Despite the method name, this method attempts to avoid actually copying the data when it is
322   * safe to do so. The exact circumstances under which a copy will or will not be performed are
323   * undocumented and subject to change.
324   *
325   * @throws IllegalArgumentException if two keys have the same value or two values have the same
326   *     key
327   * @throws NullPointerException if any key or value in {@code map} is null
328   */
329  public static <K, V> ImmutableBiMap<K, V> copyOf(Map<? extends K, ? extends V> map) {
330    if (map instanceof ImmutableBiMap) {
331      @SuppressWarnings("unchecked") // safe since map is not writable
332      ImmutableBiMap<K, V> bimap = (ImmutableBiMap<K, V>) map;
333      // TODO(lowasser): if we need to make a copy of a BiMap because the
334      // forward map is a view, don't make a copy of the non-view delegate map
335      if (!bimap.isPartialView()) {
336        return bimap;
337      }
338    }
339    return copyOf(map.entrySet());
340  }
341
342  /**
343   * Returns an immutable bimap containing the given entries. The returned bimap iterates over
344   * entries in the same order as the original iterable.
345   *
346   * @throws IllegalArgumentException if two keys have the same value or two values have the same
347   *     key
348   * @throws NullPointerException if any key, value, or entry is null
349   * @since 19.0
350   */
351  @Beta
352  public static <K, V> ImmutableBiMap<K, V> copyOf(
353      Iterable<? extends Entry<? extends K, ? extends V>> entries) {
354    @SuppressWarnings("unchecked") // we'll only be using getKey and getValue, which are covariant
355    Entry<K, V>[] entryArray = (Entry<K, V>[]) Iterables.toArray(entries, EMPTY_ENTRY_ARRAY);
356    switch (entryArray.length) {
357      case 0:
358        return of();
359      case 1:
360        Entry<K, V> entry = entryArray[0];
361        return of(entry.getKey(), entry.getValue());
362      default:
363        /*
364         * The current implementation will end up using entryArray directly, though it will write
365         * over the (arbitrary, potentially mutable) Entry objects actually stored in entryArray.
366         */
367        return RegularImmutableBiMap.fromEntries(entryArray);
368    }
369  }
370
371  ImmutableBiMap() {}
372
373  /**
374   * {@inheritDoc}
375   *
376   * <p>The inverse of an {@code ImmutableBiMap} is another {@code ImmutableBiMap}.
377   */
378  @Override
379  public abstract ImmutableBiMap<V, K> inverse();
380
381  /**
382   * Returns an immutable set of the values in this map, in the same order they appear in {@link
383   * #entrySet}.
384   */
385  @Override
386  public ImmutableSet<V> values() {
387    return inverse().keySet();
388  }
389
390  @Override
391  final ImmutableSet<V> createValues() {
392    throw new AssertionError("should never be called");
393  }
394
395  /**
396   * Guaranteed to throw an exception and leave the bimap unmodified.
397   *
398   * @throws UnsupportedOperationException always
399   * @deprecated Unsupported operation.
400   */
401  @CanIgnoreReturnValue
402  @Deprecated
403  @Override
404  public V forcePut(K key, V value) {
405    throw new UnsupportedOperationException();
406  }
407
408  /**
409   * Serialized type for all ImmutableBiMap instances. It captures the logical contents and they are
410   * reconstructed using public factory methods. This ensures that the implementation types remain
411   * as implementation details.
412   *
413   * <p>Since the bimap is immutable, ImmutableBiMap doesn't require special logic for keeping the
414   * bimap and its inverse in sync during serialization, the way AbstractBiMap does.
415   */
416  private static class SerializedForm<K, V> extends ImmutableMap.SerializedForm<K, V> {
417    SerializedForm(ImmutableBiMap<K, V> bimap) {
418      super(bimap);
419    }
420
421    @Override
422    Builder<K, V> makeBuilder(int size) {
423      return new Builder<>(size);
424    }
425
426    private static final long serialVersionUID = 0;
427  }
428
429  @Override
430  Object writeReplace() {
431    return new SerializedForm<>(this);
432  }
433}