001/*
002 * Copyright (C) 2007 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.checkArgument;
020import static com.google.common.base.Preconditions.checkNotNull;
021import static com.google.common.base.Predicates.compose;
022import static com.google.common.collect.CollectPreconditions.checkEntryNotNull;
023import static com.google.common.collect.CollectPreconditions.checkNonnegative;
024import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT;
025import static java.util.Collections.singletonMap;
026import static java.util.Objects.requireNonNull;
027
028import com.google.common.annotations.GwtCompatible;
029import com.google.common.annotations.GwtIncompatible;
030import com.google.common.annotations.J2ktIncompatible;
031import com.google.common.base.Converter;
032import com.google.common.base.Equivalence;
033import com.google.common.base.Function;
034import com.google.common.base.Objects;
035import com.google.common.base.Preconditions;
036import com.google.common.base.Predicate;
037import com.google.common.base.Predicates;
038import com.google.common.collect.MapDifference.ValueDifference;
039import com.google.common.primitives.Ints;
040import com.google.errorprone.annotations.CanIgnoreReturnValue;
041import com.google.errorprone.annotations.concurrent.LazyInit;
042import com.google.j2objc.annotations.RetainedWith;
043import com.google.j2objc.annotations.Weak;
044import com.google.j2objc.annotations.WeakOuter;
045import java.io.Serializable;
046import java.util.AbstractCollection;
047import java.util.AbstractMap;
048import java.util.Collection;
049import java.util.Collections;
050import java.util.Comparator;
051import java.util.EnumMap;
052import java.util.Enumeration;
053import java.util.HashMap;
054import java.util.IdentityHashMap;
055import java.util.Iterator;
056import java.util.LinkedHashMap;
057import java.util.Map;
058import java.util.Map.Entry;
059import java.util.NavigableMap;
060import java.util.NavigableSet;
061import java.util.Properties;
062import java.util.Set;
063import java.util.SortedMap;
064import java.util.SortedSet;
065import java.util.Spliterator;
066import java.util.Spliterators;
067import java.util.TreeMap;
068import java.util.concurrent.ConcurrentHashMap;
069import java.util.concurrent.ConcurrentMap;
070import java.util.function.BiConsumer;
071import java.util.function.BiFunction;
072import java.util.function.BinaryOperator;
073import java.util.function.Consumer;
074import java.util.stream.Collector;
075import javax.annotation.CheckForNull;
076import org.checkerframework.checker.nullness.qual.NonNull;
077import org.checkerframework.checker.nullness.qual.Nullable;
078
079/**
080 * Static utility methods pertaining to {@link Map} instances (including instances of {@link
081 * SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets}
082 * and {@link Queues}.
083 *
084 * <p>See the Guava User Guide article on <a href=
085 * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#maps">{@code Maps}</a>.
086 *
087 * @author Kevin Bourrillion
088 * @author Mike Bostock
089 * @author Isaac Shum
090 * @author Louis Wasserman
091 * @since 2.0
092 */
093@GwtCompatible(emulated = true)
094@ElementTypesAreNonnullByDefault
095public final class Maps {
096  private Maps() {}
097
098  private enum EntryFunction implements Function<Entry<?, ?>, @Nullable Object> {
099    KEY {
100      @Override
101      @CheckForNull
102      public Object apply(Entry<?, ?> entry) {
103        return entry.getKey();
104      }
105    },
106    VALUE {
107      @Override
108      @CheckForNull
109      public Object apply(Entry<?, ?> entry) {
110        return entry.getValue();
111      }
112    };
113  }
114
115  @SuppressWarnings("unchecked")
116  static <K extends @Nullable Object> Function<Entry<K, ?>, K> keyFunction() {
117    return (Function) EntryFunction.KEY;
118  }
119
120  @SuppressWarnings("unchecked")
121  static <V extends @Nullable Object> Function<Entry<?, V>, V> valueFunction() {
122    return (Function) EntryFunction.VALUE;
123  }
124
125  static <K extends @Nullable Object, V extends @Nullable Object> Iterator<K> keyIterator(
126      Iterator<Entry<K, V>> entryIterator) {
127    return new TransformedIterator<Entry<K, V>, K>(entryIterator) {
128      @Override
129      @ParametricNullness
130      K transform(Entry<K, V> entry) {
131        return entry.getKey();
132      }
133    };
134  }
135
136  static <K extends @Nullable Object, V extends @Nullable Object> Iterator<V> valueIterator(
137      Iterator<Entry<K, V>> entryIterator) {
138    return new TransformedIterator<Entry<K, V>, V>(entryIterator) {
139      @Override
140      @ParametricNullness
141      V transform(Entry<K, V> entry) {
142        return entry.getValue();
143      }
144    };
145  }
146
147  /**
148   * Returns an immutable map instance containing the given entries. Internally, the returned map
149   * will be backed by an {@link EnumMap}.
150   *
151   * <p>The iteration order of the returned map follows the enum's iteration order, not the order in
152   * which the elements appear in the given map.
153   *
154   * @param map the map to make an immutable copy of
155   * @return an immutable map containing those entries
156   * @since 14.0
157   */
158  @GwtCompatible(serializable = true)
159  @J2ktIncompatible
160  public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(
161      Map<K, ? extends V> map) {
162    if (map instanceof ImmutableEnumMap) {
163      @SuppressWarnings("unchecked") // safe covariant cast
164      ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map;
165      return result;
166    }
167    Iterator<? extends Entry<K, ? extends V>> entryItr = map.entrySet().iterator();
168    if (!entryItr.hasNext()) {
169      return ImmutableMap.of();
170    }
171    Entry<K, ? extends V> entry1 = entryItr.next();
172    K key1 = entry1.getKey();
173    V value1 = entry1.getValue();
174    checkEntryNotNull(key1, value1);
175    // Do something that works for j2cl, where we can't call getDeclaredClass():
176    EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1));
177    while (entryItr.hasNext()) {
178      Entry<K, ? extends V> entry = entryItr.next();
179      K key = entry.getKey();
180      V value = entry.getValue();
181      checkEntryNotNull(key, value);
182      enumMap.put(key, value);
183    }
184    return ImmutableEnumMap.asImmutable(enumMap);
185  }
186
187  /**
188   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
189   * and values are the result of applying the provided mapping functions to the input elements. The
190   * resulting implementation is specialized for enum key types. The returned map and its views will
191   * iterate over keys in their enum definition order, not encounter order.
192   *
193   * <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when
194   * the collection operation is performed. (This differs from the {@code Collector} returned by
195   * {@link java.util.stream.Collectors#toMap(java.util.function.Function,
196   * java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code
197   * IllegalStateException}.)
198   *
199   * @since 21.0
200   */
201  @J2ktIncompatible
202  public static <T extends @Nullable Object, K extends Enum<K>, V>
203      Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
204          java.util.function.Function<? super T, ? extends K> keyFunction,
205          java.util.function.Function<? super T, ? extends V> valueFunction) {
206    return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction);
207  }
208
209  /**
210   * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys
211   * and values are the result of applying the provided mapping functions to the input elements. The
212   * resulting implementation is specialized for enum key types. The returned map and its views will
213   * iterate over keys in their enum definition order, not encounter order.
214   *
215   * <p>If the mapped keys contain duplicates, the values are merged using the specified merging
216   * function.
217   *
218   * @since 21.0
219   */
220  @J2ktIncompatible
221  public static <T extends @Nullable Object, K extends Enum<K>, V>
222      Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap(
223          java.util.function.Function<? super T, ? extends K> keyFunction,
224          java.util.function.Function<? super T, ? extends V> valueFunction,
225          BinaryOperator<V> mergeFunction) {
226    return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction, mergeFunction);
227  }
228
229  /**
230   * Creates a <i>mutable</i>, empty {@code HashMap} instance.
231   *
232   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
233   *
234   * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead.
235   *
236   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
237   * use the {@code HashMap} constructor directly, taking advantage of <a
238   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
239   *
240   * @return a new, empty {@code HashMap}
241   */
242  public static <K extends @Nullable Object, V extends @Nullable Object>
243      HashMap<K, V> newHashMap() {
244    return new HashMap<>();
245  }
246
247  /**
248   * Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as the specified map.
249   *
250   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
251   *
252   * <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead.
253   *
254   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
255   * use the {@code HashMap} constructor directly, taking advantage of <a
256   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
257   *
258   * @param map the mappings to be placed in the new map
259   * @return a new {@code HashMap} initialized with the mappings from {@code map}
260   */
261  public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMap(
262      Map<? extends K, ? extends V> map) {
263    return new HashMap<>(map);
264  }
265
266  /**
267   * Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i>
268   * hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed,
269   * but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method
270   * isn't inadvertently <i>oversizing</i> the returned map.
271   *
272   * @param expectedSize the number of entries you expect to add to the returned map
273   * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries
274   *     without resizing
275   * @throws IllegalArgumentException if {@code expectedSize} is negative
276   */
277  public static <K extends @Nullable Object, V extends @Nullable Object>
278      HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
279    return new HashMap<>(capacity(expectedSize));
280  }
281
282  /**
283   * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
284   * larger than expectedSize and the load factor is ≥ its default (0.75).
285   */
286  static int capacity(int expectedSize) {
287    if (expectedSize < 3) {
288      checkNonnegative(expectedSize, "expectedSize");
289      return expectedSize + 1;
290    }
291    if (expectedSize < Ints.MAX_POWER_OF_TWO) {
292      // This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap
293      // ends up being used to compute a "threshold" size, beyond which the internal table
294      // will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where
295      // loadFactor is 0.75 by default. So with the calculation here we ensure that the
296      // threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code
297      // path when the first operation on the new map is putAll(otherMap). There, prior to
298      // https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug
299      // meant that sometimes a too-large threshold is calculated. However, this new threshold is
300      // independent of the initial capacity, except that it won't be lower than the threshold
301      // computed from that capacity. Because the internal table is only allocated on the first
302      // write, we won't see copying because of the new threshold. So it is always OK to use the
303      // calculation here.
304      return (int) Math.ceil(expectedSize / 0.75);
305    }
306    return Integer.MAX_VALUE; // any large value
307  }
308
309  /**
310   * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
311   *
312   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
313   *
314   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
315   * use the {@code LinkedHashMap} constructor directly, taking advantage of <a
316   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
317   *
318   * @return a new, empty {@code LinkedHashMap}
319   */
320  public static <K extends @Nullable Object, V extends @Nullable Object>
321      LinkedHashMap<K, V> newLinkedHashMap() {
322    return new LinkedHashMap<>();
323  }
324
325  /**
326   * Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance with the same
327   * mappings as the specified map.
328   *
329   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead.
330   *
331   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
332   * use the {@code LinkedHashMap} constructor directly, taking advantage of <a
333   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
334   *
335   * @param map the mappings to be placed in the new map
336   * @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map}
337   */
338  public static <K extends @Nullable Object, V extends @Nullable Object>
339      LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
340    return new LinkedHashMap<>(map);
341  }
342
343  /**
344   * Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it
345   * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be
346   * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
347   * that the method isn't inadvertently <i>oversizing</i> the returned map.
348   *
349   * @param expectedSize the number of entries you expect to add to the returned map
350   * @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize}
351   *     entries without resizing
352   * @throws IllegalArgumentException if {@code expectedSize} is negative
353   * @since 19.0
354   */
355  public static <K extends @Nullable Object, V extends @Nullable Object>
356      LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
357    return new LinkedHashMap<>(capacity(expectedSize));
358  }
359
360  /**
361   * Creates a new empty {@link ConcurrentHashMap} instance.
362   *
363   * @since 3.0
364   */
365  public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
366    return new ConcurrentHashMap<>();
367  }
368
369  /**
370   * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its
371   * elements.
372   *
373   * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedMap#of()} instead.
374   *
375   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
376   * use the {@code TreeMap} constructor directly, taking advantage of <a
377   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
378   *
379   * @return a new, empty {@code TreeMap}
380   */
381  public static <K extends Comparable, V extends @Nullable Object> TreeMap<K, V> newTreeMap() {
382    return new TreeMap<>();
383  }
384
385  /**
386   * Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as the specified map
387   * and using the same ordering as the specified map.
388   *
389   * <p><b>Note:</b> if mutability is not required, use {@link
390   * ImmutableSortedMap#copyOfSorted(SortedMap)} instead.
391   *
392   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
393   * use the {@code TreeMap} constructor directly, taking advantage of <a
394   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
395   *
396   * @param map the sorted map whose mappings are to be placed in the new map and whose comparator
397   *     is to be used to sort the new map
398   * @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the
399   *     comparator of {@code map}
400   */
401  public static <K extends @Nullable Object, V extends @Nullable Object> TreeMap<K, V> newTreeMap(
402      SortedMap<K, ? extends V> map) {
403    return new TreeMap<>(map);
404  }
405
406  /**
407   * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given comparator.
408   *
409   * <p><b>Note:</b> if mutability is not required, use {@code
410   * ImmutableSortedMap.orderedBy(comparator).build()} instead.
411   *
412   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
413   * use the {@code TreeMap} constructor directly, taking advantage of <a
414   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
415   *
416   * @param comparator the comparator to sort the keys with
417   * @return a new, empty {@code TreeMap}
418   */
419  public static <C extends @Nullable Object, K extends C, V extends @Nullable Object>
420      TreeMap<K, V> newTreeMap(@CheckForNull Comparator<C> comparator) {
421    // Ideally, the extra type parameter "C" shouldn't be necessary. It is a
422    // work-around of a compiler type inference quirk that prevents the
423    // following code from being compiled:
424    // Comparator<Class<?>> comparator = null;
425    // Map<Class<? extends Throwable>, String> map = newTreeMap(comparator);
426    return new TreeMap<>(comparator);
427  }
428
429  /**
430   * Creates an {@code EnumMap} instance.
431   *
432   * @param type the key type for this map
433   * @return a new, empty {@code EnumMap}
434   */
435  public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap(
436      Class<K> type) {
437    return new EnumMap<>(checkNotNull(type));
438  }
439
440  /**
441   * Creates an {@code EnumMap} with the same mappings as the specified map.
442   *
443   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
444   * use the {@code EnumMap} constructor directly, taking advantage of <a
445   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
446   *
447   * @param map the map from which to initialize this {@code EnumMap}
448   * @return a new {@code EnumMap} initialized with the mappings from {@code map}
449   * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains
450   *     no mappings
451   */
452  public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap(
453      Map<K, ? extends V> map) {
454    return new EnumMap<>(map);
455  }
456
457  /**
458   * Creates an {@code IdentityHashMap} instance.
459   *
460   * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead,
461   * use the {@code IdentityHashMap} constructor directly, taking advantage of <a
462   * href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
463   *
464   * @return a new, empty {@code IdentityHashMap}
465   */
466  public static <K extends @Nullable Object, V extends @Nullable Object>
467      IdentityHashMap<K, V> newIdentityHashMap() {
468    return new IdentityHashMap<>();
469  }
470
471  /**
472   * Computes the difference between two maps. This difference is an immutable snapshot of the state
473   * of the maps at the time this method is called. It will never change, even if the maps change at
474   * a later time.
475   *
476   * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
477   * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
478   *
479   * <p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code
480   * left.equals(right)} instead of this method.
481   *
482   * @param left the map to treat as the "left" map for purposes of comparison
483   * @param right the map to treat as the "right" map for purposes of comparison
484   * @return the difference between the two maps
485   */
486  public static <K extends @Nullable Object, V extends @Nullable Object>
487      MapDifference<K, V> difference(
488          Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
489    if (left instanceof SortedMap) {
490      @SuppressWarnings("unchecked")
491      SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left;
492      return difference(sortedLeft, right);
493    }
494    return difference(left, right, Equivalence.equals());
495  }
496
497  /**
498   * Computes the difference between two maps. This difference is an immutable snapshot of the state
499   * of the maps at the time this method is called. It will never change, even if the maps change at
500   * a later time.
501   *
502   * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps
503   * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}.
504   *
505   * @param left the map to treat as the "left" map for purposes of comparison
506   * @param right the map to treat as the "right" map for purposes of comparison
507   * @param valueEquivalence the equivalence relationship to use to compare values
508   * @return the difference between the two maps
509   * @since 10.0
510   */
511  public static <K extends @Nullable Object, V extends @Nullable Object>
512      MapDifference<K, V> difference(
513          Map<? extends K, ? extends V> left,
514          Map<? extends K, ? extends V> right,
515          Equivalence<? super @NonNull V> valueEquivalence) {
516    Preconditions.checkNotNull(valueEquivalence);
517
518    Map<K, V> onlyOnLeft = newLinkedHashMap();
519    Map<K, V> onlyOnRight = new LinkedHashMap<>(right); // will whittle it down
520    Map<K, V> onBoth = newLinkedHashMap();
521    Map<K, MapDifference.ValueDifference<V>> differences = newLinkedHashMap();
522    doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
523    return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
524  }
525
526  /**
527   * Computes the difference between two sorted maps, using the comparator of the left map, or
528   * {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This
529   * difference is an immutable snapshot of the state of the maps at the time this method is called.
530   * It will never change, even if the maps change at a later time.
531   *
532   * <p>Since this method uses {@code TreeMap} instances internally, the keys of the right map must
533   * all compare as distinct according to the comparator of the left map.
534   *
535   * <p><b>Note:</b>If you only need to know whether two sorted maps have the same mappings, call
536   * {@code left.equals(right)} instead of this method.
537   *
538   * @param left the map to treat as the "left" map for purposes of comparison
539   * @param right the map to treat as the "right" map for purposes of comparison
540   * @return the difference between the two maps
541   * @since 11.0
542   */
543  public static <K extends @Nullable Object, V extends @Nullable Object>
544      SortedMapDifference<K, V> difference(
545          SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
546    checkNotNull(left);
547    checkNotNull(right);
548    Comparator<? super K> comparator = orNaturalOrder(left.comparator());
549    SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator);
550    SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator);
551    onlyOnRight.putAll(right); // will whittle it down
552    SortedMap<K, V> onBoth = Maps.newTreeMap(comparator);
553    SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator);
554
555    doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
556    return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences);
557  }
558
559  private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference(
560      Map<? extends K, ? extends V> left,
561      Map<? extends K, ? extends V> right,
562      Equivalence<? super @NonNull V> valueEquivalence,
563      Map<K, V> onlyOnLeft,
564      Map<K, V> onlyOnRight,
565      Map<K, V> onBoth,
566      Map<K, MapDifference.ValueDifference<V>> differences) {
567    for (Entry<? extends K, ? extends V> entry : left.entrySet()) {
568      K leftKey = entry.getKey();
569      V leftValue = entry.getValue();
570      if (right.containsKey(leftKey)) {
571        /*
572         * The cast is safe because onlyOnRight contains all the keys of right.
573         *
574         * TODO(cpovirk): Consider checking onlyOnRight.containsKey instead of right.containsKey.
575         * That could change behavior if the input maps use different equivalence relations (and so
576         * a key that appears once in `right` might appear multiple times in `left`). We don't
577         * guarantee behavior in that case, anyway, and the current behavior is likely undesirable.
578         * So that's either a reason to feel free to change it or a reason to not bother thinking
579         * further about this.
580         */
581        V rightValue = uncheckedCastNullableTToT(onlyOnRight.remove(leftKey));
582        if (valueEquivalence.equivalent(leftValue, rightValue)) {
583          onBoth.put(leftKey, leftValue);
584        } else {
585          differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue));
586        }
587      } else {
588        onlyOnLeft.put(leftKey, leftValue);
589      }
590    }
591  }
592
593  private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> unmodifiableMap(
594      Map<K, ? extends V> map) {
595    if (map instanceof SortedMap) {
596      return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map);
597    } else {
598      return Collections.unmodifiableMap(map);
599    }
600  }
601
602  static class MapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object>
603      implements MapDifference<K, V> {
604    final Map<K, V> onlyOnLeft;
605    final Map<K, V> onlyOnRight;
606    final Map<K, V> onBoth;
607    final Map<K, ValueDifference<V>> differences;
608
609    MapDifferenceImpl(
610        Map<K, V> onlyOnLeft,
611        Map<K, V> onlyOnRight,
612        Map<K, V> onBoth,
613        Map<K, ValueDifference<V>> differences) {
614      this.onlyOnLeft = unmodifiableMap(onlyOnLeft);
615      this.onlyOnRight = unmodifiableMap(onlyOnRight);
616      this.onBoth = unmodifiableMap(onBoth);
617      this.differences = unmodifiableMap(differences);
618    }
619
620    @Override
621    public boolean areEqual() {
622      return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty();
623    }
624
625    @Override
626    public Map<K, V> entriesOnlyOnLeft() {
627      return onlyOnLeft;
628    }
629
630    @Override
631    public Map<K, V> entriesOnlyOnRight() {
632      return onlyOnRight;
633    }
634
635    @Override
636    public Map<K, V> entriesInCommon() {
637      return onBoth;
638    }
639
640    @Override
641    public Map<K, ValueDifference<V>> entriesDiffering() {
642      return differences;
643    }
644
645    @Override
646    public boolean equals(@CheckForNull Object object) {
647      if (object == this) {
648        return true;
649      }
650      if (object instanceof MapDifference) {
651        MapDifference<?, ?> other = (MapDifference<?, ?>) object;
652        return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft())
653            && entriesOnlyOnRight().equals(other.entriesOnlyOnRight())
654            && entriesInCommon().equals(other.entriesInCommon())
655            && entriesDiffering().equals(other.entriesDiffering());
656      }
657      return false;
658    }
659
660    @Override
661    public int hashCode() {
662      return Objects.hashCode(
663          entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering());
664    }
665
666    @Override
667    public String toString() {
668      if (areEqual()) {
669        return "equal";
670      }
671
672      StringBuilder result = new StringBuilder("not equal");
673      if (!onlyOnLeft.isEmpty()) {
674        result.append(": only on left=").append(onlyOnLeft);
675      }
676      if (!onlyOnRight.isEmpty()) {
677        result.append(": only on right=").append(onlyOnRight);
678      }
679      if (!differences.isEmpty()) {
680        result.append(": value differences=").append(differences);
681      }
682      return result.toString();
683    }
684  }
685
686  static class ValueDifferenceImpl<V extends @Nullable Object>
687      implements MapDifference.ValueDifference<V> {
688    @ParametricNullness private final V left;
689    @ParametricNullness private final V right;
690
691    static <V extends @Nullable Object> ValueDifference<V> create(
692        @ParametricNullness V left, @ParametricNullness V right) {
693      return new ValueDifferenceImpl<V>(left, right);
694    }
695
696    private ValueDifferenceImpl(@ParametricNullness V left, @ParametricNullness V right) {
697      this.left = left;
698      this.right = right;
699    }
700
701    @Override
702    @ParametricNullness
703    public V leftValue() {
704      return left;
705    }
706
707    @Override
708    @ParametricNullness
709    public V rightValue() {
710      return right;
711    }
712
713    @Override
714    public boolean equals(@CheckForNull Object object) {
715      if (object instanceof MapDifference.ValueDifference) {
716        MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object;
717        return Objects.equal(this.left, that.leftValue())
718            && Objects.equal(this.right, that.rightValue());
719      }
720      return false;
721    }
722
723    @Override
724    public int hashCode() {
725      return Objects.hashCode(left, right);
726    }
727
728    @Override
729    public String toString() {
730      return "(" + left + ", " + right + ")";
731    }
732  }
733
734  static class SortedMapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object>
735      extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> {
736    SortedMapDifferenceImpl(
737        SortedMap<K, V> onlyOnLeft,
738        SortedMap<K, V> onlyOnRight,
739        SortedMap<K, V> onBoth,
740        SortedMap<K, ValueDifference<V>> differences) {
741      super(onlyOnLeft, onlyOnRight, onBoth, differences);
742    }
743
744    @Override
745    public SortedMap<K, ValueDifference<V>> entriesDiffering() {
746      return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering();
747    }
748
749    @Override
750    public SortedMap<K, V> entriesInCommon() {
751      return (SortedMap<K, V>) super.entriesInCommon();
752    }
753
754    @Override
755    public SortedMap<K, V> entriesOnlyOnLeft() {
756      return (SortedMap<K, V>) super.entriesOnlyOnLeft();
757    }
758
759    @Override
760    public SortedMap<K, V> entriesOnlyOnRight() {
761      return (SortedMap<K, V>) super.entriesOnlyOnRight();
762    }
763  }
764
765  /**
766   * Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}.
767   * This method is an abomination of generics; the only purpose of this method is to contain the
768   * ugly type-casting in one place.
769   */
770  @SuppressWarnings("unchecked")
771  static <E extends @Nullable Object> Comparator<? super E> orNaturalOrder(
772      @CheckForNull Comparator<? super E> comparator) {
773    if (comparator != null) { // can't use ? : because of javac bug 5080917
774      return comparator;
775    }
776    return (Comparator<E>) Ordering.natural();
777  }
778
779  /**
780   * Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are
781   * computed on demand using {@code function}. To get an immutable <i>copy</i> instead, use {@link
782   * #toMap(Iterable, Function)}.
783   *
784   * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
785   * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
786   * entrySet} views of the returned map iterate in the same order as the backing set.
787   *
788   * <p>Modifications to the backing set are read through to the returned map. The returned map
789   * supports removal operations if the backing set does. Removal operations write through to the
790   * backing set. The returned map does not support put operations.
791   *
792   * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
793   * set does not contain {@code null}, because the view cannot stop {@code null} from being added
794   * to the set.
795   *
796   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
797   * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
798   * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
799   * calling methods on the resulting map view.
800   *
801   * @since 14.0
802   */
803  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> asMap(
804      Set<K> set, Function<? super K, V> function) {
805    return new AsMapView<>(set, function);
806  }
807
808  /**
809   * Returns a view of the sorted set as a map, mapping keys from the set according to the specified
810   * function.
811   *
812   * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
813   * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
814   * entrySet} views of the returned map iterate in the same order as the backing set.
815   *
816   * <p>Modifications to the backing set are read through to the returned map. The returned map
817   * supports removal operations if the backing set does. Removal operations write through to the
818   * backing set. The returned map does not support put operations.
819   *
820   * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
821   * set does not contain {@code null}, because the view cannot stop {@code null} from being added
822   * to the set.
823   *
824   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
825   * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
826   * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
827   * calling methods on the resulting map view.
828   *
829   * @since 14.0
830   */
831  public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> asMap(
832      SortedSet<K> set, Function<? super K, V> function) {
833    return new SortedAsMapView<>(set, function);
834  }
835
836  /**
837   * Returns a view of the navigable set as a map, mapping keys from the set according to the
838   * specified function.
839   *
840   * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping
841   * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code
842   * entrySet} views of the returned map iterate in the same order as the backing set.
843   *
844   * <p>Modifications to the backing set are read through to the returned map. The returned map
845   * supports removal operations if the backing set does. Removal operations write through to the
846   * backing set. The returned map does not support put operations.
847   *
848   * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the
849   * set does not contain {@code null}, because the view cannot stop {@code null} from being added
850   * to the set.
851   *
852   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K},
853   * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for
854   * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when
855   * calling methods on the resulting map view.
856   *
857   * @since 14.0
858   */
859  @GwtIncompatible // NavigableMap
860  public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> asMap(
861      NavigableSet<K> set, Function<? super K, V> function) {
862    return new NavigableAsMapView<>(set, function);
863  }
864
865  private static class AsMapView<K extends @Nullable Object, V extends @Nullable Object>
866      extends ViewCachingAbstractMap<K, V> {
867
868    private final Set<K> set;
869    final Function<? super K, V> function;
870
871    Set<K> backingSet() {
872      return set;
873    }
874
875    AsMapView(Set<K> set, Function<? super K, V> function) {
876      this.set = checkNotNull(set);
877      this.function = checkNotNull(function);
878    }
879
880    @Override
881    public Set<K> createKeySet() {
882      return removeOnlySet(backingSet());
883    }
884
885    @Override
886    Collection<V> createValues() {
887      return Collections2.transform(set, function);
888    }
889
890    @Override
891    public int size() {
892      return backingSet().size();
893    }
894
895    @Override
896    public boolean containsKey(@CheckForNull Object key) {
897      return backingSet().contains(key);
898    }
899
900    @Override
901    @CheckForNull
902    public V get(@CheckForNull Object key) {
903      return getOrDefault(key, null);
904    }
905
906    @Override
907    @CheckForNull
908    public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
909      if (Collections2.safeContains(backingSet(), key)) {
910        @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
911        K k = (K) key;
912        return function.apply(k);
913      } else {
914        return defaultValue;
915      }
916    }
917
918    @Override
919    @CheckForNull
920    public V remove(@CheckForNull Object key) {
921      if (backingSet().remove(key)) {
922        @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
923        K k = (K) key;
924        return function.apply(k);
925      } else {
926        return null;
927      }
928    }
929
930    @Override
931    public void clear() {
932      backingSet().clear();
933    }
934
935    @Override
936    protected Set<Entry<K, V>> createEntrySet() {
937      @WeakOuter
938      class EntrySetImpl extends EntrySet<K, V> {
939        @Override
940        Map<K, V> map() {
941          return AsMapView.this;
942        }
943
944        @Override
945        public Iterator<Entry<K, V>> iterator() {
946          return asMapEntryIterator(backingSet(), function);
947        }
948      }
949      return new EntrySetImpl();
950    }
951
952    @Override
953    public void forEach(BiConsumer<? super K, ? super V> action) {
954      checkNotNull(action);
955      // avoids allocation of entries
956      backingSet().forEach(k -> action.accept(k, function.apply(k)));
957    }
958  }
959
960  static <K extends @Nullable Object, V extends @Nullable Object>
961      Iterator<Entry<K, V>> asMapEntryIterator(Set<K> set, final Function<? super K, V> function) {
962    return new TransformedIterator<K, Entry<K, V>>(set.iterator()) {
963      @Override
964      Entry<K, V> transform(@ParametricNullness final K key) {
965        return immutableEntry(key, function.apply(key));
966      }
967    };
968  }
969
970  private static class SortedAsMapView<K extends @Nullable Object, V extends @Nullable Object>
971      extends AsMapView<K, V> implements SortedMap<K, V> {
972
973    SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) {
974      super(set, function);
975    }
976
977    @Override
978    SortedSet<K> backingSet() {
979      return (SortedSet<K>) super.backingSet();
980    }
981
982    @Override
983    @CheckForNull
984    public Comparator<? super K> comparator() {
985      return backingSet().comparator();
986    }
987
988    @Override
989    public Set<K> keySet() {
990      return removeOnlySortedSet(backingSet());
991    }
992
993    @Override
994    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
995      return asMap(backingSet().subSet(fromKey, toKey), function);
996    }
997
998    @Override
999    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
1000      return asMap(backingSet().headSet(toKey), function);
1001    }
1002
1003    @Override
1004    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
1005      return asMap(backingSet().tailSet(fromKey), function);
1006    }
1007
1008    @Override
1009    @ParametricNullness
1010    public K firstKey() {
1011      return backingSet().first();
1012    }
1013
1014    @Override
1015    @ParametricNullness
1016    public K lastKey() {
1017      return backingSet().last();
1018    }
1019  }
1020
1021  @GwtIncompatible // NavigableMap
1022  private static final class NavigableAsMapView<
1023          K extends @Nullable Object, V extends @Nullable Object>
1024      extends AbstractNavigableMap<K, V> {
1025    /*
1026     * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the
1027     * NavigableMap methods.
1028     */
1029
1030    private final NavigableSet<K> set;
1031    private final Function<? super K, V> function;
1032
1033    NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) {
1034      this.set = checkNotNull(ks);
1035      this.function = checkNotNull(vFunction);
1036    }
1037
1038    @Override
1039    public NavigableMap<K, V> subMap(
1040        @ParametricNullness K fromKey,
1041        boolean fromInclusive,
1042        @ParametricNullness K toKey,
1043        boolean toInclusive) {
1044      return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function);
1045    }
1046
1047    @Override
1048    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
1049      return asMap(set.headSet(toKey, inclusive), function);
1050    }
1051
1052    @Override
1053    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
1054      return asMap(set.tailSet(fromKey, inclusive), function);
1055    }
1056
1057    @Override
1058    @CheckForNull
1059    public Comparator<? super K> comparator() {
1060      return set.comparator();
1061    }
1062
1063    @Override
1064    @CheckForNull
1065    public V get(@CheckForNull Object key) {
1066      return getOrDefault(key, null);
1067    }
1068
1069    @Override
1070    @CheckForNull
1071    public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) {
1072      if (Collections2.safeContains(set, key)) {
1073        @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it
1074        K k = (K) key;
1075        return function.apply(k);
1076      } else {
1077        return defaultValue;
1078      }
1079    }
1080
1081    @Override
1082    public void clear() {
1083      set.clear();
1084    }
1085
1086    @Override
1087    Iterator<Entry<K, V>> entryIterator() {
1088      return asMapEntryIterator(set, function);
1089    }
1090
1091    @Override
1092    Spliterator<Entry<K, V>> entrySpliterator() {
1093      return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e)));
1094    }
1095
1096    @Override
1097    public void forEach(BiConsumer<? super K, ? super V> action) {
1098      set.forEach(k -> action.accept(k, function.apply(k)));
1099    }
1100
1101    @Override
1102    Iterator<Entry<K, V>> descendingEntryIterator() {
1103      return descendingMap().entrySet().iterator();
1104    }
1105
1106    @Override
1107    public NavigableSet<K> navigableKeySet() {
1108      return removeOnlyNavigableSet(set);
1109    }
1110
1111    @Override
1112    public int size() {
1113      return set.size();
1114    }
1115
1116    @Override
1117    public NavigableMap<K, V> descendingMap() {
1118      return asMap(set.descendingSet(), function);
1119    }
1120  }
1121
1122  private static <E extends @Nullable Object> Set<E> removeOnlySet(final Set<E> set) {
1123    return new ForwardingSet<E>() {
1124      @Override
1125      protected Set<E> delegate() {
1126        return set;
1127      }
1128
1129      @Override
1130      public boolean add(@ParametricNullness E element) {
1131        throw new UnsupportedOperationException();
1132      }
1133
1134      @Override
1135      public boolean addAll(Collection<? extends E> es) {
1136        throw new UnsupportedOperationException();
1137      }
1138    };
1139  }
1140
1141  private static <E extends @Nullable Object> SortedSet<E> removeOnlySortedSet(
1142      final SortedSet<E> set) {
1143    return new ForwardingSortedSet<E>() {
1144      @Override
1145      protected SortedSet<E> delegate() {
1146        return set;
1147      }
1148
1149      @Override
1150      public boolean add(@ParametricNullness E element) {
1151        throw new UnsupportedOperationException();
1152      }
1153
1154      @Override
1155      public boolean addAll(Collection<? extends E> es) {
1156        throw new UnsupportedOperationException();
1157      }
1158
1159      @Override
1160      public SortedSet<E> headSet(@ParametricNullness E toElement) {
1161        return removeOnlySortedSet(super.headSet(toElement));
1162      }
1163
1164      @Override
1165      public SortedSet<E> subSet(
1166          @ParametricNullness E fromElement, @ParametricNullness E toElement) {
1167        return removeOnlySortedSet(super.subSet(fromElement, toElement));
1168      }
1169
1170      @Override
1171      public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
1172        return removeOnlySortedSet(super.tailSet(fromElement));
1173      }
1174    };
1175  }
1176
1177  @GwtIncompatible // NavigableSet
1178  private static <E extends @Nullable Object> NavigableSet<E> removeOnlyNavigableSet(
1179      final NavigableSet<E> set) {
1180    return new ForwardingNavigableSet<E>() {
1181      @Override
1182      protected NavigableSet<E> delegate() {
1183        return set;
1184      }
1185
1186      @Override
1187      public boolean add(@ParametricNullness E element) {
1188        throw new UnsupportedOperationException();
1189      }
1190
1191      @Override
1192      public boolean addAll(Collection<? extends E> es) {
1193        throw new UnsupportedOperationException();
1194      }
1195
1196      @Override
1197      public SortedSet<E> headSet(@ParametricNullness E toElement) {
1198        return removeOnlySortedSet(super.headSet(toElement));
1199      }
1200
1201      @Override
1202      public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) {
1203        return removeOnlyNavigableSet(super.headSet(toElement, inclusive));
1204      }
1205
1206      @Override
1207      public SortedSet<E> subSet(
1208          @ParametricNullness E fromElement, @ParametricNullness E toElement) {
1209        return removeOnlySortedSet(super.subSet(fromElement, toElement));
1210      }
1211
1212      @Override
1213      public NavigableSet<E> subSet(
1214          @ParametricNullness E fromElement,
1215          boolean fromInclusive,
1216          @ParametricNullness E toElement,
1217          boolean toInclusive) {
1218        return removeOnlyNavigableSet(
1219            super.subSet(fromElement, fromInclusive, toElement, toInclusive));
1220      }
1221
1222      @Override
1223      public SortedSet<E> tailSet(@ParametricNullness E fromElement) {
1224        return removeOnlySortedSet(super.tailSet(fromElement));
1225      }
1226
1227      @Override
1228      public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) {
1229        return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive));
1230      }
1231
1232      @Override
1233      public NavigableSet<E> descendingSet() {
1234        return removeOnlyNavigableSet(super.descendingSet());
1235      }
1236    };
1237  }
1238
1239  /**
1240   * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
1241   * for each key was computed by {@code valueFunction}. The map's iteration order is the order of
1242   * the first appearance of each key in {@code keys}.
1243   *
1244   * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
1245   * valueFunction} will be applied to more than one instance of that key and, if it is, which
1246   * result will be mapped to that key in the returned map.
1247   *
1248   * <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link
1249   * Maps#asMap(Set, Function)}.
1250   *
1251   * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
1252   *     valueFunction} produces {@code null} for any key
1253   * @since 14.0
1254   */
1255  public static <K, V> ImmutableMap<K, V> toMap(
1256      Iterable<K> keys, Function<? super K, V> valueFunction) {
1257    return toMap(keys.iterator(), valueFunction);
1258  }
1259
1260  /**
1261   * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value
1262   * for each key was computed by {@code valueFunction}. The map's iteration order is the order of
1263   * the first appearance of each key in {@code keys}.
1264   *
1265   * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code
1266   * valueFunction} will be applied to more than one instance of that key and, if it is, which
1267   * result will be mapped to that key in the returned map.
1268   *
1269   * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code
1270   *     valueFunction} produces {@code null} for any key
1271   * @since 14.0
1272   */
1273  public static <K, V> ImmutableMap<K, V> toMap(
1274      Iterator<K> keys, Function<? super K, V> valueFunction) {
1275    checkNotNull(valueFunction);
1276    ImmutableMap.Builder<K, V> builder = ImmutableMap.builder();
1277    while (keys.hasNext()) {
1278      K key = keys.next();
1279      builder.put(key, valueFunction.apply(key));
1280    }
1281    // Using buildKeepingLast() so as not to fail on duplicate keys
1282    return builder.buildKeepingLast();
1283  }
1284
1285  /**
1286   * Returns a map with the given {@code values}, indexed by keys derived from those values. In
1287   * other words, each input value produces an entry in the map whose key is the result of applying
1288   * {@code keyFunction} to that value. These entries appear in the same order as the input values.
1289   * Example usage:
1290   *
1291   * <pre>{@code
1292   * Color red = new Color("red", 255, 0, 0);
1293   * ...
1294   * ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue);
1295   *
1296   * ImmutableMap<String, Color> colorForName =
1297   *     uniqueIndex(allColors, c -> c.toString());
1298   * assertThat(colorForName).containsEntry("red", red);
1299   * }</pre>
1300   *
1301   * <p>If your index may associate multiple values with each key, use {@link
1302   * Multimaps#index(Iterable, Function) Multimaps.index}.
1303   *
1304   * <p><b>Note:</b> on Java 8 and later, it is usually better to use streams. For example:
1305   *
1306   * <pre>{@code
1307   * import static com.google.common.collect.ImmutableMap.toImmutableMap;
1308   * ...
1309   * ImmutableMap<String, Color> colorForName =
1310   *     allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
1311   * }</pre>
1312   *
1313   * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys
1314   * and values in the map are.
1315   *
1316   * @param values the values to use when constructing the {@code Map}
1317   * @param keyFunction the function used to produce the key for each value
1318   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
1319   *     in the input collection to that value
1320   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
1321   *     value in the input collection
1322   * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
1323   *     keyFunction} produces {@code null} for any value
1324   */
1325  @CanIgnoreReturnValue
1326  public static <K, V> ImmutableMap<K, V> uniqueIndex(
1327      Iterable<V> values, Function<? super V, K> keyFunction) {
1328    if (values instanceof Collection) {
1329      return uniqueIndex(
1330          values.iterator(),
1331          keyFunction,
1332          ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size()));
1333    }
1334    return uniqueIndex(values.iterator(), keyFunction);
1335  }
1336
1337  /**
1338   * Returns a map with the given {@code values}, indexed by keys derived from those values. In
1339   * other words, each input value produces an entry in the map whose key is the result of applying
1340   * {@code keyFunction} to that value. These entries appear in the same order as the input values.
1341   * Example usage:
1342   *
1343   * <pre>{@code
1344   * Color red = new Color("red", 255, 0, 0);
1345   * ...
1346   * Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator();
1347   *
1348   * Map<String, Color> colorForName =
1349   *     uniqueIndex(allColors, toStringFunction());
1350   * assertThat(colorForName).containsEntry("red", red);
1351   * }</pre>
1352   *
1353   * <p>If your index may associate multiple values with each key, use {@link
1354   * Multimaps#index(Iterator, Function) Multimaps.index}.
1355   *
1356   * @param values the values to use when constructing the {@code Map}
1357   * @param keyFunction the function used to produce the key for each value
1358   * @return a map mapping the result of evaluating the function {@code keyFunction} on each value
1359   *     in the input collection to that value
1360   * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
1361   *     value in the input collection
1362   * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code
1363   *     keyFunction} produces {@code null} for any value
1364   * @since 10.0
1365   */
1366  @CanIgnoreReturnValue
1367  public static <K, V> ImmutableMap<K, V> uniqueIndex(
1368      Iterator<V> values, Function<? super V, K> keyFunction) {
1369    return uniqueIndex(values, keyFunction, ImmutableMap.builder());
1370  }
1371
1372  private static <K, V> ImmutableMap<K, V> uniqueIndex(
1373      Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) {
1374    checkNotNull(keyFunction);
1375    while (values.hasNext()) {
1376      V value = values.next();
1377      builder.put(keyFunction.apply(value), value);
1378    }
1379    try {
1380      return builder.buildOrThrow();
1381    } catch (IllegalArgumentException duplicateKeys) {
1382      throw new IllegalArgumentException(
1383          duplicateKeys.getMessage()
1384              + ". To index multiple values under a key, use Multimaps.index.");
1385    }
1386  }
1387
1388  /**
1389   * Creates an {@code ImmutableMap<String, String>} from a {@code Properties} instance. Properties
1390   * normally derive from {@code Map<Object, Object>}, but they typically contain strings, which is
1391   * awkward. This method lets you get a plain-old-{@code Map} out of a {@code Properties}.
1392   *
1393   * @param properties a {@code Properties} object to be converted
1394   * @return an immutable map containing all the entries in {@code properties}
1395   * @throws ClassCastException if any key in {@code properties} is not a {@code String}
1396   * @throws NullPointerException if any key or value in {@code properties} is null
1397   */
1398  @J2ktIncompatible
1399  @GwtIncompatible // java.util.Properties
1400  public static ImmutableMap<String, String> fromProperties(Properties properties) {
1401    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
1402
1403    for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) {
1404      /*
1405       * requireNonNull is safe because propertyNames contains only non-null elements.
1406       *
1407       * Accordingly, we have it annotated as returning `Enumeration<? extends Object>` in our
1408       * prototype checker's JDK. However, the checker still sees the return type as plain
1409       * `Enumeration<?>`, probably because of one of the following two bugs (and maybe those two
1410       * bugs are themselves just symptoms of the same underlying problem):
1411       *
1412       * https://github.com/typetools/checker-framework/issues/3030
1413       *
1414       * https://github.com/typetools/checker-framework/issues/3236
1415       */
1416      String key = (String) requireNonNull(e.nextElement());
1417      /*
1418       * requireNonNull is safe because the key came from propertyNames...
1419       *
1420       * ...except that it's possible for users to insert a string key with a non-string value, and
1421       * in that case, getProperty *will* return null.
1422       *
1423       * TODO(b/192002623): Handle that case: Either:
1424       *
1425       * - Skip non-string keys and values entirely, as proposed in the linked bug.
1426       *
1427       * - Throw ClassCastException instead of NullPointerException, as documented in the current
1428       *   Javadoc. (Note that we can't necessarily "just" change our call to `getProperty` to `get`
1429       *   because `get` does not consult the default properties.)
1430       */
1431      builder.put(key, requireNonNull(properties.getProperty(key)));
1432    }
1433
1434    return builder.buildOrThrow();
1435  }
1436
1437  /**
1438   * Returns an immutable map entry with the specified key and value. The {@link Entry#setValue}
1439   * operation throws an {@link UnsupportedOperationException}.
1440   *
1441   * <p>The returned entry is serializable.
1442   *
1443   * <p><b>Java 9 users:</b> consider using {@code java.util.Map.entry(key, value)} if the key and
1444   * value are non-null and the entry does not need to be serializable.
1445   *
1446   * @param key the key to be associated with the returned entry
1447   * @param value the value to be associated with the returned entry
1448   */
1449  @GwtCompatible(serializable = true)
1450  public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> immutableEntry(
1451      @ParametricNullness K key, @ParametricNullness V value) {
1452    return new ImmutableEntry<>(key, value);
1453  }
1454
1455  /**
1456   * Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue}
1457   * operation throws an {@link UnsupportedOperationException}, as do any operations that would
1458   * modify the returned set.
1459   *
1460   * @param entrySet the entries for which to return an unmodifiable view
1461   * @return an unmodifiable view of the entries
1462   */
1463  static <K extends @Nullable Object, V extends @Nullable Object>
1464      Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) {
1465    return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet));
1466  }
1467
1468  /**
1469   * Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation
1470   * throws an {@link UnsupportedOperationException}. This also has the side effect of redefining
1471   * {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation
1472   * of equals.
1473   *
1474   * @param entry the entry for which to return an unmodifiable view
1475   * @return an unmodifiable view of the entry
1476   */
1477  static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> unmodifiableEntry(
1478      final Entry<? extends K, ? extends V> entry) {
1479    checkNotNull(entry);
1480    return new AbstractMapEntry<K, V>() {
1481      @Override
1482      @ParametricNullness
1483      public K getKey() {
1484        return entry.getKey();
1485      }
1486
1487      @Override
1488      @ParametricNullness
1489      public V getValue() {
1490        return entry.getValue();
1491      }
1492    };
1493  }
1494
1495  static <K extends @Nullable Object, V extends @Nullable Object>
1496      UnmodifiableIterator<Entry<K, V>> unmodifiableEntryIterator(
1497          final Iterator<Entry<K, V>> entryIterator) {
1498    return new UnmodifiableIterator<Entry<K, V>>() {
1499      @Override
1500      public boolean hasNext() {
1501        return entryIterator.hasNext();
1502      }
1503
1504      @Override
1505      public Entry<K, V> next() {
1506        return unmodifiableEntry(entryIterator.next());
1507      }
1508    };
1509  }
1510
1511  /** The implementation of {@link Multimaps#unmodifiableEntries}. */
1512  static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object>
1513      extends ForwardingCollection<Entry<K, V>> {
1514    private final Collection<Entry<K, V>> entries;
1515
1516    UnmodifiableEntries(Collection<Entry<K, V>> entries) {
1517      this.entries = entries;
1518    }
1519
1520    @Override
1521    protected Collection<Entry<K, V>> delegate() {
1522      return entries;
1523    }
1524
1525    @Override
1526    public Iterator<Entry<K, V>> iterator() {
1527      return unmodifiableEntryIterator(entries.iterator());
1528    }
1529
1530    // See java.util.Collections.UnmodifiableEntrySet for details on attacks.
1531
1532    @Override
1533    public @Nullable Object[] toArray() {
1534      /*
1535       * standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can
1536       * be used with collections that may contain null. This collection never contains nulls, so we
1537       * could return `Object[]`. But this class is private and J2KT cannot change return types in
1538       * overrides, so we declare `@Nullable Object[]` as the return type.
1539       */
1540      return standardToArray();
1541    }
1542
1543    @Override
1544    @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
1545    public <T extends @Nullable Object> T[] toArray(T[] array) {
1546      return standardToArray(array);
1547    }
1548  }
1549
1550  /** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */
1551  static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object>
1552      extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> {
1553    UnmodifiableEntrySet(Set<Entry<K, V>> entries) {
1554      super(entries);
1555    }
1556
1557    // See java.util.Collections.UnmodifiableEntrySet for details on attacks.
1558
1559    @Override
1560    public boolean equals(@CheckForNull Object object) {
1561      return Sets.equalsImpl(this, object);
1562    }
1563
1564    @Override
1565    public int hashCode() {
1566      return Sets.hashCodeImpl(this);
1567    }
1568  }
1569
1570  /**
1571   * Returns a {@link Converter} that converts values using {@link BiMap#get bimap.get()}, and whose
1572   * inverse view converts values using {@link BiMap#inverse bimap.inverse()}{@code .get()}.
1573   *
1574   * <p>To use a plain {@link Map} as a {@link Function}, see {@link
1575   * com.google.common.base.Functions#forMap(Map)} or {@link
1576   * com.google.common.base.Functions#forMap(Map, Object)}.
1577   *
1578   * @since 16.0
1579   */
1580  public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) {
1581    return new BiMapConverter<>(bimap);
1582  }
1583
1584  private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable {
1585    private final BiMap<A, B> bimap;
1586
1587    BiMapConverter(BiMap<A, B> bimap) {
1588      this.bimap = checkNotNull(bimap);
1589    }
1590
1591    @Override
1592    protected B doForward(A a) {
1593      return convert(bimap, a);
1594    }
1595
1596    @Override
1597    protected A doBackward(B b) {
1598      return convert(bimap.inverse(), b);
1599    }
1600
1601    private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) {
1602      Y output = bimap.get(input);
1603      checkArgument(output != null, "No non-null mapping present for input: %s", input);
1604      return output;
1605    }
1606
1607    @Override
1608    public boolean equals(@CheckForNull Object object) {
1609      if (object instanceof BiMapConverter) {
1610        BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object;
1611        return this.bimap.equals(that.bimap);
1612      }
1613      return false;
1614    }
1615
1616    @Override
1617    public int hashCode() {
1618      return bimap.hashCode();
1619    }
1620
1621    // There's really no good way to implement toString() without printing the entire BiMap, right?
1622    @Override
1623    public String toString() {
1624      return "Maps.asConverter(" + bimap + ")";
1625    }
1626
1627    private static final long serialVersionUID = 0L;
1628  }
1629
1630  /**
1631   * Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee
1632   * serial access, it is critical that <b>all</b> access to the backing bimap is accomplished
1633   * through the returned bimap.
1634   *
1635   * <p>It is imperative that the user manually synchronize on the returned map when accessing any
1636   * of its collection views:
1637   *
1638   * <pre>{@code
1639   * BiMap<Long, String> map = Maps.synchronizedBiMap(
1640   *     HashBiMap.<Long, String>create());
1641   * ...
1642   * Set<Long> set = map.keySet();  // Needn't be in synchronized block
1643   * ...
1644   * synchronized (map) {  // Synchronizing on map, not set!
1645   *   Iterator<Long> it = set.iterator(); // Must be in synchronized block
1646   *   while (it.hasNext()) {
1647   *     foo(it.next());
1648   *   }
1649   * }
1650   * }</pre>
1651   *
1652   * <p>Failure to follow this advice may result in non-deterministic behavior.
1653   *
1654   * <p>The returned bimap will be serializable if the specified bimap is serializable.
1655   *
1656   * @param bimap the bimap to be wrapped in a synchronized view
1657   * @return a synchronized view of the specified bimap
1658   */
1659  public static <K extends @Nullable Object, V extends @Nullable Object>
1660      BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
1661    return Synchronized.biMap(bimap, null);
1662  }
1663
1664  /**
1665   * Returns an unmodifiable view of the specified bimap. This method allows modules to provide
1666   * users with "read-only" access to internal bimaps. Query operations on the returned bimap "read
1667   * through" to the specified bimap, and attempts to modify the returned map, whether direct or via
1668   * its collection views, result in an {@code UnsupportedOperationException}.
1669   *
1670   * <p>The returned bimap will be serializable if the specified bimap is serializable.
1671   *
1672   * @param bimap the bimap for which an unmodifiable view is to be returned
1673   * @return an unmodifiable view of the specified bimap
1674   */
1675  public static <K extends @Nullable Object, V extends @Nullable Object>
1676      BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) {
1677    return new UnmodifiableBiMap<>(bimap, null);
1678  }
1679
1680  /**
1681   * @see Maps#unmodifiableBiMap(BiMap)
1682   */
1683  private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object>
1684      extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable {
1685    final Map<K, V> unmodifiableMap;
1686    final BiMap<? extends K, ? extends V> delegate;
1687    @LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse;
1688    @LazyInit @CheckForNull transient Set<V> values;
1689
1690    UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) {
1691      unmodifiableMap = Collections.unmodifiableMap(delegate);
1692      this.delegate = delegate;
1693      this.inverse = inverse;
1694    }
1695
1696    @Override
1697    protected Map<K, V> delegate() {
1698      return unmodifiableMap;
1699    }
1700
1701    @Override
1702    @CheckForNull
1703    public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
1704      throw new UnsupportedOperationException();
1705    }
1706
1707    @Override
1708    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
1709      throw new UnsupportedOperationException();
1710    }
1711
1712    @Override
1713    @CheckForNull
1714    public V putIfAbsent(K key, V value) {
1715      throw new UnsupportedOperationException();
1716    }
1717
1718    @Override
1719    public boolean remove(@Nullable Object key, @Nullable Object value) {
1720      throw new UnsupportedOperationException();
1721    }
1722
1723    @Override
1724    public boolean replace(K key, V oldValue, V newValue) {
1725      throw new UnsupportedOperationException();
1726    }
1727
1728    @Override
1729    @CheckForNull
1730    public V replace(K key, V value) {
1731      throw new UnsupportedOperationException();
1732    }
1733
1734    @Override
1735    public V computeIfAbsent(
1736        K key, java.util.function.Function<? super K, ? extends V> mappingFunction) {
1737      throw new UnsupportedOperationException();
1738    }
1739
1740    @Override
1741    public V computeIfPresent(
1742        K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
1743      throw new UnsupportedOperationException();
1744    }
1745
1746    @Override
1747    public V compute(
1748        K key, BiFunction<? super K, ? super @Nullable V, ? extends V> remappingFunction) {
1749      throw new UnsupportedOperationException();
1750    }
1751
1752    @Override
1753    @CheckForNull
1754    public V merge(
1755        K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
1756      throw new UnsupportedOperationException();
1757    }
1758
1759    @Override
1760    public BiMap<V, K> inverse() {
1761      BiMap<V, K> result = inverse;
1762      return (result == null)
1763          ? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this)
1764          : result;
1765    }
1766
1767    @Override
1768    public Set<V> values() {
1769      Set<V> result = values;
1770      return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result;
1771    }
1772
1773    private static final long serialVersionUID = 0;
1774  }
1775
1776  /**
1777   * Returns a view of a map where each value is transformed by a function. All other properties of
1778   * the map, such as iteration order, are left intact. For example, the code:
1779   *
1780   * <pre>{@code
1781   * Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
1782   * Function<Integer, Double> sqrt =
1783   *     new Function<Integer, Double>() {
1784   *       public Double apply(Integer in) {
1785   *         return Math.sqrt((int) in);
1786   *       }
1787   *     };
1788   * Map<String, Double> transformed = Maps.transformValues(map, sqrt);
1789   * System.out.println(transformed);
1790   * }</pre>
1791   *
1792   * ... prints {@code {a=2.0, b=3.0}}.
1793   *
1794   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1795   * removal operations, and these are reflected in the underlying map.
1796   *
1797   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1798   * that the function is capable of accepting null input. The transformed map might contain null
1799   * values, if the function sometimes gives a null result.
1800   *
1801   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1802   *
1803   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1804   * to be a view, but it means that the function will be applied many times for bulk operations
1805   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1806   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1807   * view, copy the returned map into a new map of your choosing.
1808   */
1809  public static <
1810          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1811      Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) {
1812    return transformEntries(fromMap, asEntryTransformer(function));
1813  }
1814
1815  /**
1816   * Returns a view of a sorted map where each value is transformed by a function. All other
1817   * properties of the map, such as iteration order, are left intact. For example, the code:
1818   *
1819   * <pre>{@code
1820   * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
1821   * Function<Integer, Double> sqrt =
1822   *     new Function<Integer, Double>() {
1823   *       public Double apply(Integer in) {
1824   *         return Math.sqrt((int) in);
1825   *       }
1826   *     };
1827   * SortedMap<String, Double> transformed =
1828   *      Maps.transformValues(map, sqrt);
1829   * System.out.println(transformed);
1830   * }</pre>
1831   *
1832   * ... prints {@code {a=2.0, b=3.0}}.
1833   *
1834   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1835   * removal operations, and these are reflected in the underlying map.
1836   *
1837   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1838   * that the function is capable of accepting null input. The transformed map might contain null
1839   * values, if the function sometimes gives a null result.
1840   *
1841   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1842   *
1843   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1844   * to be a view, but it means that the function will be applied many times for bulk operations
1845   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1846   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1847   * view, copy the returned map into a new map of your choosing.
1848   *
1849   * @since 11.0
1850   */
1851  public static <
1852          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1853      SortedMap<K, V2> transformValues(
1854          SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
1855    return transformEntries(fromMap, asEntryTransformer(function));
1856  }
1857
1858  /**
1859   * Returns a view of a navigable map where each value is transformed by a function. All other
1860   * properties of the map, such as iteration order, are left intact. For example, the code:
1861   *
1862   * <pre>{@code
1863   * NavigableMap<String, Integer> map = Maps.newTreeMap();
1864   * map.put("a", 4);
1865   * map.put("b", 9);
1866   * Function<Integer, Double> sqrt =
1867   *     new Function<Integer, Double>() {
1868   *       public Double apply(Integer in) {
1869   *         return Math.sqrt((int) in);
1870   *       }
1871   *     };
1872   * NavigableMap<String, Double> transformed =
1873   *      Maps.transformNavigableValues(map, sqrt);
1874   * System.out.println(transformed);
1875   * }</pre>
1876   *
1877   * ... prints {@code {a=2.0, b=3.0}}.
1878   *
1879   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1880   * removal operations, and these are reflected in the underlying map.
1881   *
1882   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1883   * that the function is capable of accepting null input. The transformed map might contain null
1884   * values, if the function sometimes gives a null result.
1885   *
1886   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1887   *
1888   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1889   * to be a view, but it means that the function will be applied many times for bulk operations
1890   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1891   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1892   * view, copy the returned map into a new map of your choosing.
1893   *
1894   * @since 13.0
1895   */
1896  @GwtIncompatible // NavigableMap
1897  public static <
1898          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1899      NavigableMap<K, V2> transformValues(
1900          NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
1901    return transformEntries(fromMap, asEntryTransformer(function));
1902  }
1903
1904  /**
1905   * Returns a view of a map whose values are derived from the original map's entries. In contrast
1906   * to {@link #transformValues}, this method's entry-transformation logic may depend on the key as
1907   * well as the value.
1908   *
1909   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
1910   * example, the code:
1911   *
1912   * <pre>{@code
1913   * Map<String, Boolean> options =
1914   *     ImmutableMap.of("verbose", true, "sort", false);
1915   * EntryTransformer<String, Boolean, String> flagPrefixer =
1916   *     new EntryTransformer<String, Boolean, String>() {
1917   *       public String transformEntry(String key, Boolean value) {
1918   *         return value ? key : "no" + key;
1919   *       }
1920   *     };
1921   * Map<String, String> transformed =
1922   *     Maps.transformEntries(options, flagPrefixer);
1923   * System.out.println(transformed);
1924   * }</pre>
1925   *
1926   * ... prints {@code {verbose=verbose, sort=nosort}}.
1927   *
1928   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1929   * removal operations, and these are reflected in the underlying map.
1930   *
1931   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
1932   * the transformer is capable of accepting null inputs. The transformed map might contain null
1933   * values if the transformer sometimes gives a null result.
1934   *
1935   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1936   *
1937   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
1938   * map to be a view, but it means that the transformer will be applied many times for bulk
1939   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
1940   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
1941   * doesn't need to be a view, copy the returned map into a new map of your choosing.
1942   *
1943   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
1944   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
1945   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
1946   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
1947   * transformed map.
1948   *
1949   * @since 7.0
1950   */
1951  public static <
1952          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1953      Map<K, V2> transformEntries(
1954          Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1955    return new TransformedEntriesMap<>(fromMap, transformer);
1956  }
1957
1958  /**
1959   * Returns a view of a sorted map whose values are derived from the original sorted map's entries.
1960   * In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on
1961   * the key as well as the value.
1962   *
1963   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
1964   * example, the code:
1965   *
1966   * <pre>{@code
1967   * Map<String, Boolean> options =
1968   *     ImmutableSortedMap.of("verbose", true, "sort", false);
1969   * EntryTransformer<String, Boolean, String> flagPrefixer =
1970   *     new EntryTransformer<String, Boolean, String>() {
1971   *       public String transformEntry(String key, Boolean value) {
1972   *         return value ? key : "yes" + key;
1973   *       }
1974   *     };
1975   * SortedMap<String, String> transformed =
1976   *     Maps.transformEntries(options, flagPrefixer);
1977   * System.out.println(transformed);
1978   * }</pre>
1979   *
1980   * ... prints {@code {sort=yessort, verbose=verbose}}.
1981   *
1982   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1983   * removal operations, and these are reflected in the underlying map.
1984   *
1985   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
1986   * the transformer is capable of accepting null inputs. The transformed map might contain null
1987   * values if the transformer sometimes gives a null result.
1988   *
1989   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1990   *
1991   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
1992   * map to be a view, but it means that the transformer will be applied many times for bulk
1993   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
1994   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
1995   * doesn't need to be a view, copy the returned map into a new map of your choosing.
1996   *
1997   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
1998   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
1999   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
2000   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
2001   * transformed map.
2002   *
2003   * @since 11.0
2004   */
2005  public static <
2006          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2007      SortedMap<K, V2> transformEntries(
2008          SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2009    return new TransformedEntriesSortedMap<>(fromMap, transformer);
2010  }
2011
2012  /**
2013   * Returns a view of a navigable map whose values are derived from the original navigable map's
2014   * entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may
2015   * depend on the key as well as the value.
2016   *
2017   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
2018   * example, the code:
2019   *
2020   * <pre>{@code
2021   * NavigableMap<String, Boolean> options = Maps.newTreeMap();
2022   * options.put("verbose", false);
2023   * options.put("sort", true);
2024   * EntryTransformer<String, Boolean, String> flagPrefixer =
2025   *     new EntryTransformer<String, Boolean, String>() {
2026   *       public String transformEntry(String key, Boolean value) {
2027   *         return value ? key : ("yes" + key);
2028   *       }
2029   *     };
2030   * NavigableMap<String, String> transformed =
2031   *     LabsMaps.transformNavigableEntries(options, flagPrefixer);
2032   * System.out.println(transformed);
2033   * }</pre>
2034   *
2035   * ... prints {@code {sort=yessort, verbose=verbose}}.
2036   *
2037   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
2038   * removal operations, and these are reflected in the underlying map.
2039   *
2040   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
2041   * the transformer is capable of accepting null inputs. The transformed map might contain null
2042   * values if the transformer sometimes gives a null result.
2043   *
2044   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
2045   *
2046   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
2047   * map to be a view, but it means that the transformer will be applied many times for bulk
2048   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
2049   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
2050   * doesn't need to be a view, copy the returned map into a new map of your choosing.
2051   *
2052   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
2053   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
2054   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
2055   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
2056   * transformed map.
2057   *
2058   * @since 13.0
2059   */
2060  @GwtIncompatible // NavigableMap
2061  public static <
2062          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2063      NavigableMap<K, V2> transformEntries(
2064          NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2065    return new TransformedEntriesNavigableMap<>(fromMap, transformer);
2066  }
2067
2068  /**
2069   * A transformation of the value of a key-value pair, using both key and value as inputs. To apply
2070   * the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}.
2071   *
2072   * @param <K> the key type of the input and output entries
2073   * @param <V1> the value type of the input entry
2074   * @param <V2> the value type of the output entry
2075   * @since 7.0
2076   */
2077  @FunctionalInterface
2078  public interface EntryTransformer<
2079      K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> {
2080    /**
2081     * Determines an output value based on a key-value pair. This method is <i>generally
2082     * expected</i>, but not absolutely required, to have the following properties:
2083     *
2084     * <ul>
2085     *   <li>Its execution does not cause any observable side effects.
2086     *   <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
2087     *       Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that
2088     *       {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}.
2089     * </ul>
2090     *
2091     * @throws NullPointerException if the key or value is null and this transformer does not accept
2092     *     null arguments
2093     */
2094    @ParametricNullness
2095    V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value);
2096  }
2097
2098  /** Views a function as an entry transformer that ignores the entry key. */
2099  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2100      EntryTransformer<K, V1, V2> asEntryTransformer(final Function<? super V1, V2> function) {
2101    checkNotNull(function);
2102    return new EntryTransformer<K, V1, V2>() {
2103      @Override
2104      @ParametricNullness
2105      public V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value) {
2106        return function.apply(value);
2107      }
2108    };
2109  }
2110
2111  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2112      Function<V1, V2> asValueToValueFunction(
2113          final EntryTransformer<? super K, V1, V2> transformer, @ParametricNullness final K key) {
2114    checkNotNull(transformer);
2115    return new Function<V1, V2>() {
2116      @Override
2117      @ParametricNullness
2118      public V2 apply(@ParametricNullness V1 v1) {
2119        return transformer.transformEntry(key, v1);
2120      }
2121    };
2122  }
2123
2124  /** Views an entry transformer as a function from {@code Entry} to values. */
2125  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2126      Function<Entry<K, V1>, V2> asEntryToValueFunction(
2127          final EntryTransformer<? super K, ? super V1, V2> transformer) {
2128    checkNotNull(transformer);
2129    return new Function<Entry<K, V1>, V2>() {
2130      @Override
2131      @ParametricNullness
2132      public V2 apply(Entry<K, V1> entry) {
2133        return transformer.transformEntry(entry.getKey(), entry.getValue());
2134      }
2135    };
2136  }
2137
2138  /** Returns a view of an entry transformed by the specified transformer. */
2139  static <V2 extends @Nullable Object, K extends @Nullable Object, V1 extends @Nullable Object>
2140      Entry<K, V2> transformEntry(
2141          final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
2142    checkNotNull(transformer);
2143    checkNotNull(entry);
2144    return new AbstractMapEntry<K, V2>() {
2145      @Override
2146      @ParametricNullness
2147      public K getKey() {
2148        return entry.getKey();
2149      }
2150
2151      @Override
2152      @ParametricNullness
2153      public V2 getValue() {
2154        return transformer.transformEntry(entry.getKey(), entry.getValue());
2155      }
2156    };
2157  }
2158
2159  /** Views an entry transformer as a function from entries to entries. */
2160  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2161      Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
2162          final EntryTransformer<? super K, ? super V1, V2> transformer) {
2163    checkNotNull(transformer);
2164    return new Function<Entry<K, V1>, Entry<K, V2>>() {
2165      @Override
2166      public Entry<K, V2> apply(final Entry<K, V1> entry) {
2167        return transformEntry(transformer, entry);
2168      }
2169    };
2170  }
2171
2172  static class TransformedEntriesMap<
2173          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2174      extends IteratorBasedAbstractMap<K, V2> {
2175    final Map<K, V1> fromMap;
2176    final EntryTransformer<? super K, ? super V1, V2> transformer;
2177
2178    TransformedEntriesMap(
2179        Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2180      this.fromMap = checkNotNull(fromMap);
2181      this.transformer = checkNotNull(transformer);
2182    }
2183
2184    @Override
2185    public int size() {
2186      return fromMap.size();
2187    }
2188
2189    @Override
2190    public boolean containsKey(@CheckForNull Object key) {
2191      return fromMap.containsKey(key);
2192    }
2193
2194    @Override
2195    @CheckForNull
2196    public V2 get(@CheckForNull Object key) {
2197      return getOrDefault(key, null);
2198    }
2199
2200    // safe as long as the user followed the <b>Warning</b> in the javadoc
2201    @SuppressWarnings("unchecked")
2202    @Override
2203    @CheckForNull
2204    public V2 getOrDefault(@CheckForNull Object key, @CheckForNull V2 defaultValue) {
2205      V1 value = fromMap.get(key);
2206      if (value != null || fromMap.containsKey(key)) {
2207        // The cast is safe because of the containsKey check.
2208        return transformer.transformEntry((K) key, uncheckedCastNullableTToT(value));
2209      }
2210      return defaultValue;
2211    }
2212
2213    // safe as long as the user followed the <b>Warning</b> in the javadoc
2214    @SuppressWarnings("unchecked")
2215    @Override
2216    @CheckForNull
2217    public V2 remove(@CheckForNull Object key) {
2218      return fromMap.containsKey(key)
2219          // The cast is safe because of the containsKey check.
2220          ? transformer.transformEntry((K) key, uncheckedCastNullableTToT(fromMap.remove(key)))
2221          : null;
2222    }
2223
2224    @Override
2225    public void clear() {
2226      fromMap.clear();
2227    }
2228
2229    @Override
2230    public Set<K> keySet() {
2231      return fromMap.keySet();
2232    }
2233
2234    @Override
2235    Iterator<Entry<K, V2>> entryIterator() {
2236      return Iterators.transform(
2237          fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
2238    }
2239
2240    @Override
2241    Spliterator<Entry<K, V2>> entrySpliterator() {
2242      return CollectSpliterators.map(
2243          fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
2244    }
2245
2246    @Override
2247    public void forEach(BiConsumer<? super K, ? super V2> action) {
2248      checkNotNull(action);
2249      // avoids creating new Entry<K, V2> objects
2250      fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1)));
2251    }
2252
2253    @Override
2254    public Collection<V2> values() {
2255      return new Values<>(this);
2256    }
2257  }
2258
2259  static class TransformedEntriesSortedMap<
2260          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2261      extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
2262
2263    protected SortedMap<K, V1> fromMap() {
2264      return (SortedMap<K, V1>) fromMap;
2265    }
2266
2267    TransformedEntriesSortedMap(
2268        SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2269      super(fromMap, transformer);
2270    }
2271
2272    @Override
2273    @CheckForNull
2274    public Comparator<? super K> comparator() {
2275      return fromMap().comparator();
2276    }
2277
2278    @Override
2279    @ParametricNullness
2280    public K firstKey() {
2281      return fromMap().firstKey();
2282    }
2283
2284    @Override
2285    public SortedMap<K, V2> headMap(@ParametricNullness K toKey) {
2286      return transformEntries(fromMap().headMap(toKey), transformer);
2287    }
2288
2289    @Override
2290    @ParametricNullness
2291    public K lastKey() {
2292      return fromMap().lastKey();
2293    }
2294
2295    @Override
2296    public SortedMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
2297      return transformEntries(fromMap().subMap(fromKey, toKey), transformer);
2298    }
2299
2300    @Override
2301    public SortedMap<K, V2> tailMap(@ParametricNullness K fromKey) {
2302      return transformEntries(fromMap().tailMap(fromKey), transformer);
2303    }
2304  }
2305
2306  @GwtIncompatible // NavigableMap
2307  private static class TransformedEntriesNavigableMap<
2308          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2309      extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> {
2310
2311    TransformedEntriesNavigableMap(
2312        NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2313      super(fromMap, transformer);
2314    }
2315
2316    @Override
2317    @CheckForNull
2318    public Entry<K, V2> ceilingEntry(@ParametricNullness K key) {
2319      return transformEntry(fromMap().ceilingEntry(key));
2320    }
2321
2322    @Override
2323    @CheckForNull
2324    public K ceilingKey(@ParametricNullness K key) {
2325      return fromMap().ceilingKey(key);
2326    }
2327
2328    @Override
2329    public NavigableSet<K> descendingKeySet() {
2330      return fromMap().descendingKeySet();
2331    }
2332
2333    @Override
2334    public NavigableMap<K, V2> descendingMap() {
2335      return transformEntries(fromMap().descendingMap(), transformer);
2336    }
2337
2338    @Override
2339    @CheckForNull
2340    public Entry<K, V2> firstEntry() {
2341      return transformEntry(fromMap().firstEntry());
2342    }
2343
2344    @Override
2345    @CheckForNull
2346    public Entry<K, V2> floorEntry(@ParametricNullness K key) {
2347      return transformEntry(fromMap().floorEntry(key));
2348    }
2349
2350    @Override
2351    @CheckForNull
2352    public K floorKey(@ParametricNullness K key) {
2353      return fromMap().floorKey(key);
2354    }
2355
2356    @Override
2357    public NavigableMap<K, V2> headMap(@ParametricNullness K toKey) {
2358      return headMap(toKey, false);
2359    }
2360
2361    @Override
2362    public NavigableMap<K, V2> headMap(@ParametricNullness K toKey, boolean inclusive) {
2363      return transformEntries(fromMap().headMap(toKey, inclusive), transformer);
2364    }
2365
2366    @Override
2367    @CheckForNull
2368    public Entry<K, V2> higherEntry(@ParametricNullness K key) {
2369      return transformEntry(fromMap().higherEntry(key));
2370    }
2371
2372    @Override
2373    @CheckForNull
2374    public K higherKey(@ParametricNullness K key) {
2375      return fromMap().higherKey(key);
2376    }
2377
2378    @Override
2379    @CheckForNull
2380    public Entry<K, V2> lastEntry() {
2381      return transformEntry(fromMap().lastEntry());
2382    }
2383
2384    @Override
2385    @CheckForNull
2386    public Entry<K, V2> lowerEntry(@ParametricNullness K key) {
2387      return transformEntry(fromMap().lowerEntry(key));
2388    }
2389
2390    @Override
2391    @CheckForNull
2392    public K lowerKey(@ParametricNullness K key) {
2393      return fromMap().lowerKey(key);
2394    }
2395
2396    @Override
2397    public NavigableSet<K> navigableKeySet() {
2398      return fromMap().navigableKeySet();
2399    }
2400
2401    @Override
2402    @CheckForNull
2403    public Entry<K, V2> pollFirstEntry() {
2404      return transformEntry(fromMap().pollFirstEntry());
2405    }
2406
2407    @Override
2408    @CheckForNull
2409    public Entry<K, V2> pollLastEntry() {
2410      return transformEntry(fromMap().pollLastEntry());
2411    }
2412
2413    @Override
2414    public NavigableMap<K, V2> subMap(
2415        @ParametricNullness K fromKey,
2416        boolean fromInclusive,
2417        @ParametricNullness K toKey,
2418        boolean toInclusive) {
2419      return transformEntries(
2420          fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer);
2421    }
2422
2423    @Override
2424    public NavigableMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
2425      return subMap(fromKey, true, toKey, false);
2426    }
2427
2428    @Override
2429    public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey) {
2430      return tailMap(fromKey, true);
2431    }
2432
2433    @Override
2434    public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
2435      return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer);
2436    }
2437
2438    @CheckForNull
2439    private Entry<K, V2> transformEntry(@CheckForNull Entry<K, V1> entry) {
2440      return (entry == null) ? null : Maps.transformEntry(transformer, entry);
2441    }
2442
2443    @Override
2444    protected NavigableMap<K, V1> fromMap() {
2445      return (NavigableMap<K, V1>) super.fromMap();
2446    }
2447  }
2448
2449  static <K extends @Nullable Object> Predicate<Entry<K, ?>> keyPredicateOnEntries(
2450      Predicate<? super K> keyPredicate) {
2451    return compose(keyPredicate, Maps.<K>keyFunction());
2452  }
2453
2454  static <V extends @Nullable Object> Predicate<Entry<?, V>> valuePredicateOnEntries(
2455      Predicate<? super V> valuePredicate) {
2456    return compose(valuePredicate, Maps.<V>valueFunction());
2457  }
2458
2459  /**
2460   * Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The
2461   * returned map is a live view of {@code unfiltered}; changes to one affect the other.
2462   *
2463   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2464   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2465   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2466   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2467   *
2468   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2469   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2470   * map.
2471   *
2472   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2473   *
2474   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2475   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2476   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2477   *
2478   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2479   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2480   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2481   */
2482  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterKeys(
2483      Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2484    checkNotNull(keyPredicate);
2485    Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
2486    return (unfiltered instanceof AbstractFilteredMap)
2487        ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
2488        : new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate);
2489  }
2490
2491  /**
2492   * Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a
2493   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2494   * other.
2495   *
2496   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2497   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2498   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2499   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2500   *
2501   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2502   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2503   * map.
2504   *
2505   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2506   *
2507   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2508   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2509   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2510   *
2511   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2512   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2513   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2514   *
2515   * @since 11.0
2516   */
2517  public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterKeys(
2518      SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2519    // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
2520    // performance.
2521    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2522  }
2523
2524  /**
2525   * Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a
2526   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2527   * other.
2528   *
2529   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2530   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2531   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2532   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2533   *
2534   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2535   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2536   * map.
2537   *
2538   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2539   *
2540   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2541   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2542   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2543   *
2544   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2545   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2546   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2547   *
2548   * @since 14.0
2549   */
2550  @GwtIncompatible // NavigableMap
2551  public static <K extends @Nullable Object, V extends @Nullable Object>
2552      NavigableMap<K, V> filterKeys(
2553          NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2554    // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
2555    // performance.
2556    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2557  }
2558
2559  /**
2560   * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
2561   * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2562   *
2563   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2564   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2565   * and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()},
2566   * {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}.
2567   *
2568   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2569   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2570   * bimap.
2571   *
2572   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2573   *
2574   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
2575   * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
2576   * needed, it may be faster to copy the filtered bimap and use the copy.
2577   *
2578   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2579   * at {@link Predicate#apply}.
2580   *
2581   * @since 14.0
2582   */
2583  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterKeys(
2584      BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2585    checkNotNull(keyPredicate);
2586    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2587  }
2588
2589  /**
2590   * Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate.
2591   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2592   *
2593   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2594   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2595   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2596   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2597   *
2598   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2599   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2600   * map.
2601   *
2602   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2603   *
2604   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2605   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2606   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2607   *
2608   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2609   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2610   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2611   */
2612  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterValues(
2613      Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2614    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2615  }
2616
2617  /**
2618   * Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a
2619   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2620   * other.
2621   *
2622   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2623   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2624   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2625   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2626   *
2627   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2628   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2629   * map.
2630   *
2631   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2632   *
2633   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2634   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2635   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2636   *
2637   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2638   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2639   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2640   *
2641   * @since 11.0
2642   */
2643  public static <K extends @Nullable Object, V extends @Nullable Object>
2644      SortedMap<K, V> filterValues(
2645          SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2646    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2647  }
2648
2649  /**
2650   * Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a
2651   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2652   * other.
2653   *
2654   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2655   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2656   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2657   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2658   *
2659   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2660   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2661   * map.
2662   *
2663   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2664   *
2665   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2666   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2667   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2668   *
2669   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2670   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2671   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2672   *
2673   * @since 14.0
2674   */
2675  @GwtIncompatible // NavigableMap
2676  public static <K extends @Nullable Object, V extends @Nullable Object>
2677      NavigableMap<K, V> filterValues(
2678          NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2679    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2680  }
2681
2682  /**
2683   * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate.
2684   * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2685   *
2686   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2687   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2688   * and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code
2689   * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
2690   * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method
2691   * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the
2692   * predicate.
2693   *
2694   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2695   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2696   * bimap.
2697   *
2698   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2699   *
2700   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
2701   * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
2702   * needed, it may be faster to copy the filtered bimap and use the copy.
2703   *
2704   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2705   * at {@link Predicate#apply}.
2706   *
2707   * @since 14.0
2708   */
2709  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterValues(
2710      BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2711    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2712  }
2713
2714  /**
2715   * Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The
2716   * returned map is a live view of {@code unfiltered}; changes to one affect the other.
2717   *
2718   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2719   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2720   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2721   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2722   * map's entries have a {@link Entry#setValue} method that throws an {@link
2723   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2724   * predicate.
2725   *
2726   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2727   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2728   *
2729   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2730   *
2731   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2732   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2733   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2734   *
2735   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2736   * at {@link Predicate#apply}.
2737   */
2738  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterEntries(
2739      Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2740    checkNotNull(entryPredicate);
2741    return (unfiltered instanceof AbstractFilteredMap)
2742        ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
2743        : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2744  }
2745
2746  /**
2747   * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
2748   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2749   *
2750   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2751   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2752   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2753   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2754   * map's entries have a {@link Entry#setValue} method that throws an {@link
2755   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2756   * predicate.
2757   *
2758   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2759   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2760   *
2761   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2762   *
2763   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2764   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2765   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2766   *
2767   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2768   * at {@link Predicate#apply}.
2769   *
2770   * @since 11.0
2771   */
2772  public static <K extends @Nullable Object, V extends @Nullable Object>
2773      SortedMap<K, V> filterEntries(
2774          SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2775    checkNotNull(entryPredicate);
2776    return (unfiltered instanceof FilteredEntrySortedMap)
2777        ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
2778        : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2779  }
2780
2781  /**
2782   * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
2783   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2784   *
2785   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2786   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2787   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2788   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2789   * map's entries have a {@link Entry#setValue} method that throws an {@link
2790   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2791   * predicate.
2792   *
2793   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2794   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2795   *
2796   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2797   *
2798   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2799   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2800   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2801   *
2802   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2803   * at {@link Predicate#apply}.
2804   *
2805   * @since 14.0
2806   */
2807  @GwtIncompatible // NavigableMap
2808  public static <K extends @Nullable Object, V extends @Nullable Object>
2809      NavigableMap<K, V> filterEntries(
2810          NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2811    checkNotNull(entryPredicate);
2812    return (unfiltered instanceof FilteredEntryNavigableMap)
2813        ? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate)
2814        : new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2815  }
2816
2817  /**
2818   * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2819   * returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2820   *
2821   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2822   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2823   * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
2824   * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
2825   * IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method
2826   * that throws an {@link IllegalArgumentException} when the existing key and the provided value
2827   * don't satisfy the predicate.
2828   *
2829   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2830   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2831   * bimap.
2832   *
2833   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2834   *
2835   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value
2836   * mapping in the underlying bimap and determine which satisfy the filter. When a live view is
2837   * <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
2838   *
2839   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2840   * at {@link Predicate#apply}.
2841   *
2842   * @since 14.0
2843   */
2844  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterEntries(
2845      BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2846    checkNotNull(unfiltered);
2847    checkNotNull(entryPredicate);
2848    return (unfiltered instanceof FilteredEntryBiMap)
2849        ? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
2850        : new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate);
2851  }
2852
2853  /**
2854   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2855   * map.
2856   */
2857  private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterFiltered(
2858      AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2859    return new FilteredEntryMap<>(
2860        map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
2861  }
2862
2863  /**
2864   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2865   * sorted map.
2866   */
2867  private static <K extends @Nullable Object, V extends @Nullable Object>
2868      SortedMap<K, V> filterFiltered(
2869          FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2870    Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
2871    return new FilteredEntrySortedMap<>(map.sortedMap(), predicate);
2872  }
2873
2874  /**
2875   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2876   * navigable map.
2877   */
2878  @GwtIncompatible // NavigableMap
2879  private static <K extends @Nullable Object, V extends @Nullable Object>
2880      NavigableMap<K, V> filterFiltered(
2881          FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2882    Predicate<Entry<K, V>> predicate =
2883        Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate);
2884    return new FilteredEntryNavigableMap<>(map.unfiltered, predicate);
2885  }
2886
2887  /**
2888   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2889   * map.
2890   */
2891  private static <K extends @Nullable Object, V extends @Nullable Object>
2892      BiMap<K, V> filterFiltered(
2893          FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2894    Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
2895    return new FilteredEntryBiMap<>(map.unfiltered(), predicate);
2896  }
2897
2898  private abstract static class AbstractFilteredMap<
2899          K extends @Nullable Object, V extends @Nullable Object>
2900      extends ViewCachingAbstractMap<K, V> {
2901    final Map<K, V> unfiltered;
2902    final Predicate<? super Entry<K, V>> predicate;
2903
2904    AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
2905      this.unfiltered = unfiltered;
2906      this.predicate = predicate;
2907    }
2908
2909    boolean apply(@CheckForNull Object key, @ParametricNullness V value) {
2910      // This method is called only when the key is in the map (or about to be added to the map),
2911      // implying that key is a K.
2912      @SuppressWarnings({"unchecked", "nullness"})
2913      K k = (K) key;
2914      return predicate.apply(Maps.immutableEntry(k, value));
2915    }
2916
2917    @Override
2918    @CheckForNull
2919    public V put(@ParametricNullness K key, @ParametricNullness V value) {
2920      checkArgument(apply(key, value));
2921      return unfiltered.put(key, value);
2922    }
2923
2924    @Override
2925    public void putAll(Map<? extends K, ? extends V> map) {
2926      for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
2927        checkArgument(apply(entry.getKey(), entry.getValue()));
2928      }
2929      unfiltered.putAll(map);
2930    }
2931
2932    @Override
2933    public boolean containsKey(@CheckForNull Object key) {
2934      return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
2935    }
2936
2937    @Override
2938    @CheckForNull
2939    public V get(@CheckForNull Object key) {
2940      V value = unfiltered.get(key);
2941      return ((value != null) && apply(key, value)) ? value : null;
2942    }
2943
2944    @Override
2945    public boolean isEmpty() {
2946      return entrySet().isEmpty();
2947    }
2948
2949    @Override
2950    @CheckForNull
2951    public V remove(@CheckForNull Object key) {
2952      return containsKey(key) ? unfiltered.remove(key) : null;
2953    }
2954
2955    @Override
2956    Collection<V> createValues() {
2957      return new FilteredMapValues<>(this, unfiltered, predicate);
2958    }
2959  }
2960
2961  private static final class FilteredMapValues<
2962          K extends @Nullable Object, V extends @Nullable Object>
2963      extends Maps.Values<K, V> {
2964    final Map<K, V> unfiltered;
2965    final Predicate<? super Entry<K, V>> predicate;
2966
2967    FilteredMapValues(
2968        Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
2969      super(filteredMap);
2970      this.unfiltered = unfiltered;
2971      this.predicate = predicate;
2972    }
2973
2974    @Override
2975    public boolean remove(@CheckForNull Object o) {
2976      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
2977      while (entryItr.hasNext()) {
2978        Entry<K, V> entry = entryItr.next();
2979        if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) {
2980          entryItr.remove();
2981          return true;
2982        }
2983      }
2984      return false;
2985    }
2986
2987    @Override
2988    public boolean removeAll(Collection<?> collection) {
2989      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
2990      boolean result = false;
2991      while (entryItr.hasNext()) {
2992        Entry<K, V> entry = entryItr.next();
2993        if (predicate.apply(entry) && collection.contains(entry.getValue())) {
2994          entryItr.remove();
2995          result = true;
2996        }
2997      }
2998      return result;
2999    }
3000
3001    @Override
3002    public boolean retainAll(Collection<?> collection) {
3003      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
3004      boolean result = false;
3005      while (entryItr.hasNext()) {
3006        Entry<K, V> entry = entryItr.next();
3007        if (predicate.apply(entry) && !collection.contains(entry.getValue())) {
3008          entryItr.remove();
3009          result = true;
3010        }
3011      }
3012      return result;
3013    }
3014
3015    @Override
3016    public @Nullable Object[] toArray() {
3017      // creating an ArrayList so filtering happens once
3018      return Lists.newArrayList(iterator()).toArray();
3019    }
3020
3021    @Override
3022    @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
3023    public <T extends @Nullable Object> T[] toArray(T[] array) {
3024      return Lists.newArrayList(iterator()).toArray(array);
3025    }
3026  }
3027
3028  private static class FilteredKeyMap<K extends @Nullable Object, V extends @Nullable Object>
3029      extends AbstractFilteredMap<K, V> {
3030    final Predicate<? super K> keyPredicate;
3031
3032    FilteredKeyMap(
3033        Map<K, V> unfiltered,
3034        Predicate<? super K> keyPredicate,
3035        Predicate<? super Entry<K, V>> entryPredicate) {
3036      super(unfiltered, entryPredicate);
3037      this.keyPredicate = keyPredicate;
3038    }
3039
3040    @Override
3041    protected Set<Entry<K, V>> createEntrySet() {
3042      return Sets.filter(unfiltered.entrySet(), predicate);
3043    }
3044
3045    @Override
3046    Set<K> createKeySet() {
3047      return Sets.filter(unfiltered.keySet(), keyPredicate);
3048    }
3049
3050    // The cast is called only when the key is in the unfiltered map, implying
3051    // that key is a K.
3052    @Override
3053    @SuppressWarnings("unchecked")
3054    public boolean containsKey(@CheckForNull Object key) {
3055      return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
3056    }
3057  }
3058
3059  static class FilteredEntryMap<K extends @Nullable Object, V extends @Nullable Object>
3060      extends AbstractFilteredMap<K, V> {
3061    /**
3062     * Entries in this set satisfy the predicate, but they don't validate the input to {@code
3063     * Entry.setValue()}.
3064     */
3065    final Set<Entry<K, V>> filteredEntrySet;
3066
3067    FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3068      super(unfiltered, entryPredicate);
3069      filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
3070    }
3071
3072    @Override
3073    protected Set<Entry<K, V>> createEntrySet() {
3074      return new EntrySet();
3075    }
3076
3077    @WeakOuter
3078    private class EntrySet extends ForwardingSet<Entry<K, V>> {
3079      @Override
3080      protected Set<Entry<K, V>> delegate() {
3081        return filteredEntrySet;
3082      }
3083
3084      @Override
3085      public Iterator<Entry<K, V>> iterator() {
3086        return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
3087          @Override
3088          Entry<K, V> transform(final Entry<K, V> entry) {
3089            return new ForwardingMapEntry<K, V>() {
3090              @Override
3091              protected Entry<K, V> delegate() {
3092                return entry;
3093              }
3094
3095              @Override
3096              @ParametricNullness
3097              public V setValue(@ParametricNullness V newValue) {
3098                checkArgument(apply(getKey(), newValue));
3099                return super.setValue(newValue);
3100              }
3101            };
3102          }
3103        };
3104      }
3105    }
3106
3107    @Override
3108    Set<K> createKeySet() {
3109      return new KeySet();
3110    }
3111
3112    static <K extends @Nullable Object, V extends @Nullable Object> boolean removeAllKeys(
3113        Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
3114      Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
3115      boolean result = false;
3116      while (entryItr.hasNext()) {
3117        Entry<K, V> entry = entryItr.next();
3118        if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) {
3119          entryItr.remove();
3120          result = true;
3121        }
3122      }
3123      return result;
3124    }
3125
3126    static <K extends @Nullable Object, V extends @Nullable Object> boolean retainAllKeys(
3127        Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
3128      Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
3129      boolean result = false;
3130      while (entryItr.hasNext()) {
3131        Entry<K, V> entry = entryItr.next();
3132        if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) {
3133          entryItr.remove();
3134          result = true;
3135        }
3136      }
3137      return result;
3138    }
3139
3140    @WeakOuter
3141    class KeySet extends Maps.KeySet<K, V> {
3142      KeySet() {
3143        super(FilteredEntryMap.this);
3144      }
3145
3146      @Override
3147      public boolean remove(@CheckForNull Object o) {
3148        if (containsKey(o)) {
3149          unfiltered.remove(o);
3150          return true;
3151        }
3152        return false;
3153      }
3154
3155      @Override
3156      public boolean removeAll(Collection<?> collection) {
3157        return removeAllKeys(unfiltered, predicate, collection);
3158      }
3159
3160      @Override
3161      public boolean retainAll(Collection<?> collection) {
3162        return retainAllKeys(unfiltered, predicate, collection);
3163      }
3164
3165      @Override
3166      public @Nullable Object[] toArray() {
3167        // creating an ArrayList so filtering happens once
3168        return Lists.newArrayList(iterator()).toArray();
3169      }
3170
3171      @Override
3172      @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
3173      public <T extends @Nullable Object> T[] toArray(T[] array) {
3174        return Lists.newArrayList(iterator()).toArray(array);
3175      }
3176    }
3177  }
3178
3179  private static class FilteredEntrySortedMap<
3180          K extends @Nullable Object, V extends @Nullable Object>
3181      extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
3182
3183    FilteredEntrySortedMap(
3184        SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3185      super(unfiltered, entryPredicate);
3186    }
3187
3188    SortedMap<K, V> sortedMap() {
3189      return (SortedMap<K, V>) unfiltered;
3190    }
3191
3192    @Override
3193    public SortedSet<K> keySet() {
3194      return (SortedSet<K>) super.keySet();
3195    }
3196
3197    @Override
3198    SortedSet<K> createKeySet() {
3199      return new SortedKeySet();
3200    }
3201
3202    @WeakOuter
3203    class SortedKeySet extends KeySet implements SortedSet<K> {
3204      @Override
3205      @CheckForNull
3206      public Comparator<? super K> comparator() {
3207        return sortedMap().comparator();
3208      }
3209
3210      @Override
3211      public SortedSet<K> subSet(
3212          @ParametricNullness K fromElement, @ParametricNullness K toElement) {
3213        return (SortedSet<K>) subMap(fromElement, toElement).keySet();
3214      }
3215
3216      @Override
3217      public SortedSet<K> headSet(@ParametricNullness K toElement) {
3218        return (SortedSet<K>) headMap(toElement).keySet();
3219      }
3220
3221      @Override
3222      public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
3223        return (SortedSet<K>) tailMap(fromElement).keySet();
3224      }
3225
3226      @Override
3227      @ParametricNullness
3228      public K first() {
3229        return firstKey();
3230      }
3231
3232      @Override
3233      @ParametricNullness
3234      public K last() {
3235        return lastKey();
3236      }
3237    }
3238
3239    @Override
3240    @CheckForNull
3241    public Comparator<? super K> comparator() {
3242      return sortedMap().comparator();
3243    }
3244
3245    @Override
3246    @ParametricNullness
3247    public K firstKey() {
3248      // correctly throws NoSuchElementException when filtered map is empty.
3249      return keySet().iterator().next();
3250    }
3251
3252    @Override
3253    @ParametricNullness
3254    public K lastKey() {
3255      SortedMap<K, V> headMap = sortedMap();
3256      while (true) {
3257        // correctly throws NoSuchElementException when filtered map is empty.
3258        K key = headMap.lastKey();
3259        // The cast is safe because the key is taken from the map.
3260        if (apply(key, uncheckedCastNullableTToT(unfiltered.get(key)))) {
3261          return key;
3262        }
3263        headMap = sortedMap().headMap(key);
3264      }
3265    }
3266
3267    @Override
3268    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
3269      return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate);
3270    }
3271
3272    @Override
3273    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
3274      return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate);
3275    }
3276
3277    @Override
3278    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
3279      return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate);
3280    }
3281  }
3282
3283  @GwtIncompatible // NavigableMap
3284  private static class FilteredEntryNavigableMap<
3285          K extends @Nullable Object, V extends @Nullable Object>
3286      extends AbstractNavigableMap<K, V> {
3287    /*
3288     * It's less code to extend AbstractNavigableMap and forward the filtering logic to
3289     * FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap
3290     * methods.
3291     */
3292
3293    private final NavigableMap<K, V> unfiltered;
3294    private final Predicate<? super Entry<K, V>> entryPredicate;
3295    private final Map<K, V> filteredDelegate;
3296
3297    FilteredEntryNavigableMap(
3298        NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3299      this.unfiltered = checkNotNull(unfiltered);
3300      this.entryPredicate = entryPredicate;
3301      this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate);
3302    }
3303
3304    @Override
3305    @CheckForNull
3306    public Comparator<? super K> comparator() {
3307      return unfiltered.comparator();
3308    }
3309
3310    @Override
3311    public NavigableSet<K> navigableKeySet() {
3312      return new Maps.NavigableKeySet<K, V>(this) {
3313        @Override
3314        public boolean removeAll(Collection<?> collection) {
3315          return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection);
3316        }
3317
3318        @Override
3319        public boolean retainAll(Collection<?> collection) {
3320          return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection);
3321        }
3322      };
3323    }
3324
3325    @Override
3326    public Collection<V> values() {
3327      return new FilteredMapValues<>(this, unfiltered, entryPredicate);
3328    }
3329
3330    @Override
3331    Iterator<Entry<K, V>> entryIterator() {
3332      return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate);
3333    }
3334
3335    @Override
3336    Iterator<Entry<K, V>> descendingEntryIterator() {
3337      return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate);
3338    }
3339
3340    @Override
3341    public int size() {
3342      return filteredDelegate.size();
3343    }
3344
3345    @Override
3346    public boolean isEmpty() {
3347      return !Iterables.any(unfiltered.entrySet(), entryPredicate);
3348    }
3349
3350    @Override
3351    @CheckForNull
3352    public V get(@CheckForNull Object key) {
3353      return filteredDelegate.get(key);
3354    }
3355
3356    @Override
3357    public boolean containsKey(@CheckForNull Object key) {
3358      return filteredDelegate.containsKey(key);
3359    }
3360
3361    @Override
3362    @CheckForNull
3363    public V put(@ParametricNullness K key, @ParametricNullness V value) {
3364      return filteredDelegate.put(key, value);
3365    }
3366
3367    @Override
3368    @CheckForNull
3369    public V remove(@CheckForNull Object key) {
3370      return filteredDelegate.remove(key);
3371    }
3372
3373    @Override
3374    public void putAll(Map<? extends K, ? extends V> m) {
3375      filteredDelegate.putAll(m);
3376    }
3377
3378    @Override
3379    public void clear() {
3380      filteredDelegate.clear();
3381    }
3382
3383    @Override
3384    public Set<Entry<K, V>> entrySet() {
3385      return filteredDelegate.entrySet();
3386    }
3387
3388    @Override
3389    @CheckForNull
3390    public Entry<K, V> pollFirstEntry() {
3391      return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate);
3392    }
3393
3394    @Override
3395    @CheckForNull
3396    public Entry<K, V> pollLastEntry() {
3397      return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate);
3398    }
3399
3400    @Override
3401    public NavigableMap<K, V> descendingMap() {
3402      return filterEntries(unfiltered.descendingMap(), entryPredicate);
3403    }
3404
3405    @Override
3406    public NavigableMap<K, V> subMap(
3407        @ParametricNullness K fromKey,
3408        boolean fromInclusive,
3409        @ParametricNullness K toKey,
3410        boolean toInclusive) {
3411      return filterEntries(
3412          unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate);
3413    }
3414
3415    @Override
3416    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
3417      return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate);
3418    }
3419
3420    @Override
3421    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
3422      return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate);
3423    }
3424  }
3425
3426  static final class FilteredEntryBiMap<K extends @Nullable Object, V extends @Nullable Object>
3427      extends FilteredEntryMap<K, V> implements BiMap<K, V> {
3428    @RetainedWith private final BiMap<V, K> inverse;
3429
3430    private static <K extends @Nullable Object, V extends @Nullable Object>
3431        Predicate<Entry<V, K>> inversePredicate(
3432            final Predicate<? super Entry<K, V>> forwardPredicate) {
3433      return new Predicate<Entry<V, K>>() {
3434        @Override
3435        public boolean apply(Entry<V, K> input) {
3436          return forwardPredicate.apply(Maps.immutableEntry(input.getValue(), input.getKey()));
3437        }
3438      };
3439    }
3440
3441    FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) {
3442      super(delegate, predicate);
3443      this.inverse =
3444          new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this);
3445    }
3446
3447    private FilteredEntryBiMap(
3448        BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) {
3449      super(delegate, predicate);
3450      this.inverse = inverse;
3451    }
3452
3453    BiMap<K, V> unfiltered() {
3454      return (BiMap<K, V>) unfiltered;
3455    }
3456
3457    @Override
3458    @CheckForNull
3459    public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
3460      checkArgument(apply(key, value));
3461      return unfiltered().forcePut(key, value);
3462    }
3463
3464    @Override
3465    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3466      unfiltered()
3467          .replaceAll(
3468              (key, value) ->
3469                  predicate.apply(Maps.immutableEntry(key, value))
3470                      ? function.apply(key, value)
3471                      : value);
3472    }
3473
3474    @Override
3475    public BiMap<V, K> inverse() {
3476      return inverse;
3477    }
3478
3479    @Override
3480    public Set<V> values() {
3481      return inverse.keySet();
3482    }
3483  }
3484
3485  /**
3486   * Returns an unmodifiable view of the specified navigable map. Query operations on the returned
3487   * map read through to the specified map, and attempts to modify the returned map, whether direct
3488   * or via its views, result in an {@code UnsupportedOperationException}.
3489   *
3490   * <p>The returned navigable map will be serializable if the specified navigable map is
3491   * serializable.
3492   *
3493   * <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K,
3494   * V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code
3495   * comparator()} method might return a {@code Comparator<? extends K>}, which works only on a
3496   * particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which
3497   * must work on any type of {@code K}.
3498   *
3499   * @param map the navigable map for which an unmodifiable view is to be returned
3500   * @return an unmodifiable view of the specified navigable map
3501   * @since 12.0
3502   */
3503  @GwtIncompatible // NavigableMap
3504  public static <K extends @Nullable Object, V extends @Nullable Object>
3505      NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) {
3506    checkNotNull(map);
3507    if (map instanceof UnmodifiableNavigableMap) {
3508      @SuppressWarnings("unchecked") // covariant
3509      NavigableMap<K, V> result = (NavigableMap<K, V>) map;
3510      return result;
3511    } else {
3512      return new UnmodifiableNavigableMap<>(map);
3513    }
3514  }
3515
3516  @CheckForNull
3517  private static <K extends @Nullable Object, V extends @Nullable Object>
3518      Entry<K, V> unmodifiableOrNull(@CheckForNull Entry<K, ? extends V> entry) {
3519    return (entry == null) ? null : Maps.unmodifiableEntry(entry);
3520  }
3521
3522  @GwtIncompatible // NavigableMap
3523  static class UnmodifiableNavigableMap<K extends @Nullable Object, V extends @Nullable Object>
3524      extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable {
3525    private final NavigableMap<K, ? extends V> delegate;
3526
3527    UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) {
3528      this.delegate = delegate;
3529    }
3530
3531    UnmodifiableNavigableMap(
3532        NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) {
3533      this.delegate = delegate;
3534      this.descendingMap = descendingMap;
3535    }
3536
3537    @Override
3538    protected SortedMap<K, V> delegate() {
3539      return Collections.unmodifiableSortedMap(delegate);
3540    }
3541
3542    @Override
3543    @CheckForNull
3544    public Entry<K, V> lowerEntry(@ParametricNullness K key) {
3545      return unmodifiableOrNull(delegate.lowerEntry(key));
3546    }
3547
3548    @Override
3549    @CheckForNull
3550    public K lowerKey(@ParametricNullness K key) {
3551      return delegate.lowerKey(key);
3552    }
3553
3554    @Override
3555    @CheckForNull
3556    public Entry<K, V> floorEntry(@ParametricNullness K key) {
3557      return unmodifiableOrNull(delegate.floorEntry(key));
3558    }
3559
3560    @Override
3561    @CheckForNull
3562    public K floorKey(@ParametricNullness K key) {
3563      return delegate.floorKey(key);
3564    }
3565
3566    @Override
3567    @CheckForNull
3568    public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
3569      return unmodifiableOrNull(delegate.ceilingEntry(key));
3570    }
3571
3572    @Override
3573    @CheckForNull
3574    public K ceilingKey(@ParametricNullness K key) {
3575      return delegate.ceilingKey(key);
3576    }
3577
3578    @Override
3579    @CheckForNull
3580    public Entry<K, V> higherEntry(@ParametricNullness K key) {
3581      return unmodifiableOrNull(delegate.higherEntry(key));
3582    }
3583
3584    @Override
3585    @CheckForNull
3586    public K higherKey(@ParametricNullness K key) {
3587      return delegate.higherKey(key);
3588    }
3589
3590    @Override
3591    @CheckForNull
3592    public Entry<K, V> firstEntry() {
3593      return unmodifiableOrNull(delegate.firstEntry());
3594    }
3595
3596    @Override
3597    @CheckForNull
3598    public Entry<K, V> lastEntry() {
3599      return unmodifiableOrNull(delegate.lastEntry());
3600    }
3601
3602    @Override
3603    @CheckForNull
3604    public final Entry<K, V> pollFirstEntry() {
3605      throw new UnsupportedOperationException();
3606    }
3607
3608    @Override
3609    @CheckForNull
3610    public final Entry<K, V> pollLastEntry() {
3611      throw new UnsupportedOperationException();
3612    }
3613
3614    @Override
3615    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3616      throw new UnsupportedOperationException();
3617    }
3618
3619    @Override
3620    @CheckForNull
3621    public V putIfAbsent(K key, V value) {
3622      throw new UnsupportedOperationException();
3623    }
3624
3625    @Override
3626    public boolean remove(@Nullable Object key, @Nullable Object value) {
3627      throw new UnsupportedOperationException();
3628    }
3629
3630    @Override
3631    public boolean replace(K key, V oldValue, V newValue) {
3632      throw new UnsupportedOperationException();
3633    }
3634
3635    @Override
3636    @CheckForNull
3637    public V replace(K key, V value) {
3638      throw new UnsupportedOperationException();
3639    }
3640
3641    @Override
3642    public V computeIfAbsent(
3643        K key, java.util.function.Function<? super K, ? extends V> mappingFunction) {
3644      throw new UnsupportedOperationException();
3645    }
3646
3647    @Override
3648    public V computeIfPresent(
3649        K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
3650      throw new UnsupportedOperationException();
3651    }
3652
3653    @Override
3654    public V compute(
3655        K key, BiFunction<? super K, ? super @Nullable V, ? extends V> remappingFunction) {
3656      throw new UnsupportedOperationException();
3657    }
3658
3659    @Override
3660    @CheckForNull
3661    public V merge(
3662        K key, V value, BiFunction<? super V, ? super V, ? extends @Nullable V> function) {
3663      throw new UnsupportedOperationException();
3664    }
3665
3666    @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
3667
3668    @Override
3669    public NavigableMap<K, V> descendingMap() {
3670      UnmodifiableNavigableMap<K, V> result = descendingMap;
3671      return (result == null)
3672          ? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this)
3673          : result;
3674    }
3675
3676    @Override
3677    public Set<K> keySet() {
3678      return navigableKeySet();
3679    }
3680
3681    @Override
3682    public NavigableSet<K> navigableKeySet() {
3683      return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
3684    }
3685
3686    @Override
3687    public NavigableSet<K> descendingKeySet() {
3688      return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
3689    }
3690
3691    @Override
3692    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
3693      return subMap(fromKey, true, toKey, false);
3694    }
3695
3696    @Override
3697    public NavigableMap<K, V> subMap(
3698        @ParametricNullness K fromKey,
3699        boolean fromInclusive,
3700        @ParametricNullness K toKey,
3701        boolean toInclusive) {
3702      return Maps.unmodifiableNavigableMap(
3703          delegate.subMap(fromKey, fromInclusive, toKey, toInclusive));
3704    }
3705
3706    @Override
3707    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
3708      return headMap(toKey, false);
3709    }
3710
3711    @Override
3712    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
3713      return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive));
3714    }
3715
3716    @Override
3717    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
3718      return tailMap(fromKey, true);
3719    }
3720
3721    @Override
3722    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
3723      return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive));
3724    }
3725  }
3726
3727  /**
3728   * Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In
3729   * order to guarantee serial access, it is critical that <b>all</b> access to the backing
3730   * navigable map is accomplished through the returned navigable map (or its views).
3731   *
3732   * <p>It is imperative that the user manually synchronize on the returned navigable map when
3733   * iterating over any of its collection views, or the collections views of any of its {@code
3734   * descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views.
3735   *
3736   * <pre>{@code
3737   * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
3738   *
3739   * // Needn't be in synchronized block
3740   * NavigableSet<K> set = map.navigableKeySet();
3741   *
3742   * synchronized (map) { // Synchronizing on map, not set!
3743   *   Iterator<K> it = set.iterator(); // Must be in synchronized block
3744   *   while (it.hasNext()) {
3745   *     foo(it.next());
3746   *   }
3747   * }
3748   * }</pre>
3749   *
3750   * <p>or:
3751   *
3752   * <pre>{@code
3753   * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
3754   * NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true);
3755   *
3756   * // Needn't be in synchronized block
3757   * NavigableSet<K> set2 = map2.descendingKeySet();
3758   *
3759   * synchronized (map) { // Synchronizing on map, not map2 or set2!
3760   *   Iterator<K> it = set2.iterator(); // Must be in synchronized block
3761   *   while (it.hasNext()) {
3762   *     foo(it.next());
3763   *   }
3764   * }
3765   * }</pre>
3766   *
3767   * <p>Failure to follow this advice may result in non-deterministic behavior.
3768   *
3769   * <p>The returned navigable map will be serializable if the specified navigable map is
3770   * serializable.
3771   *
3772   * @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map.
3773   * @return a synchronized view of the specified navigable map.
3774   * @since 13.0
3775   */
3776  @GwtIncompatible // NavigableMap
3777  public static <K extends @Nullable Object, V extends @Nullable Object>
3778      NavigableMap<K, V> synchronizedNavigableMap(NavigableMap<K, V> navigableMap) {
3779    return Synchronized.navigableMap(navigableMap);
3780  }
3781
3782  /**
3783   * {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and
3784   * entrySet views.
3785   */
3786  @GwtCompatible
3787  abstract static class ViewCachingAbstractMap<
3788          K extends @Nullable Object, V extends @Nullable Object>
3789      extends AbstractMap<K, V> {
3790    /**
3791     * Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
3792     * once on a given map, at the time when {@code entrySet} is first called.
3793     */
3794    abstract Set<Entry<K, V>> createEntrySet();
3795
3796    @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
3797
3798    @Override
3799    public Set<Entry<K, V>> entrySet() {
3800      Set<Entry<K, V>> result = entrySet;
3801      return (result == null) ? entrySet = createEntrySet() : result;
3802    }
3803
3804    @LazyInit @CheckForNull private transient Set<K> keySet;
3805
3806    @Override
3807    public Set<K> keySet() {
3808      Set<K> result = keySet;
3809      return (result == null) ? keySet = createKeySet() : result;
3810    }
3811
3812    Set<K> createKeySet() {
3813      return new KeySet<>(this);
3814    }
3815
3816    @LazyInit @CheckForNull private transient Collection<V> values;
3817
3818    @Override
3819    public Collection<V> values() {
3820      Collection<V> result = values;
3821      return (result == null) ? values = createValues() : result;
3822    }
3823
3824    Collection<V> createValues() {
3825      return new Values<>(this);
3826    }
3827  }
3828
3829  abstract static class IteratorBasedAbstractMap<
3830          K extends @Nullable Object, V extends @Nullable Object>
3831      extends AbstractMap<K, V> {
3832    @Override
3833    public abstract int size();
3834
3835    abstract Iterator<Entry<K, V>> entryIterator();
3836
3837    Spliterator<Entry<K, V>> entrySpliterator() {
3838      return Spliterators.spliterator(
3839          entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT);
3840    }
3841
3842    @Override
3843    public Set<Entry<K, V>> entrySet() {
3844      return new EntrySet<K, V>() {
3845        @Override
3846        Map<K, V> map() {
3847          return IteratorBasedAbstractMap.this;
3848        }
3849
3850        @Override
3851        public Iterator<Entry<K, V>> iterator() {
3852          return entryIterator();
3853        }
3854
3855        @Override
3856        public Spliterator<Entry<K, V>> spliterator() {
3857          return entrySpliterator();
3858        }
3859
3860        @Override
3861        public void forEach(Consumer<? super Entry<K, V>> action) {
3862          forEachEntry(action);
3863        }
3864      };
3865    }
3866
3867    void forEachEntry(Consumer<? super Entry<K, V>> action) {
3868      entryIterator().forEachRemaining(action);
3869    }
3870
3871    @Override
3872    public void clear() {
3873      Iterators.clear(entryIterator());
3874    }
3875  }
3876
3877  /**
3878   * Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code
3879   * NullPointerException}.
3880   */
3881  @CheckForNull
3882  static <V extends @Nullable Object> V safeGet(Map<?, V> map, @CheckForNull Object key) {
3883    checkNotNull(map);
3884    try {
3885      return map.get(key);
3886    } catch (ClassCastException | NullPointerException e) {
3887      return null;
3888    }
3889  }
3890
3891  /**
3892   * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and
3893   * {@code NullPointerException}.
3894   */
3895  static boolean safeContainsKey(Map<?, ?> map, @CheckForNull Object key) {
3896    checkNotNull(map);
3897    try {
3898      return map.containsKey(key);
3899    } catch (ClassCastException | NullPointerException e) {
3900      return false;
3901    }
3902  }
3903
3904  /**
3905   * Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code
3906   * NullPointerException}.
3907   */
3908  @CheckForNull
3909  static <V extends @Nullable Object> V safeRemove(Map<?, V> map, @CheckForNull Object key) {
3910    checkNotNull(map);
3911    try {
3912      return map.remove(key);
3913    } catch (ClassCastException | NullPointerException e) {
3914      return null;
3915    }
3916  }
3917
3918  /** An admittedly inefficient implementation of {@link Map#containsKey}. */
3919  static boolean containsKeyImpl(Map<?, ?> map, @CheckForNull Object key) {
3920    return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
3921  }
3922
3923  /** An implementation of {@link Map#containsValue}. */
3924  static boolean containsValueImpl(Map<?, ?> map, @CheckForNull Object value) {
3925    return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
3926  }
3927
3928  /**
3929   * Implements {@code Collection.contains} safely for forwarding collections of map entries. If
3930   * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
3931   * protect against a possible nefarious equals method.
3932   *
3933   * <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding
3934   * collection.
3935   *
3936   * @param c the delegate (unwrapped) collection of map entries
3937   * @param o the object that might be contained in {@code c}
3938   * @return {@code true} if {@code c} contains {@code o}
3939   */
3940  static <K extends @Nullable Object, V extends @Nullable Object> boolean containsEntryImpl(
3941      Collection<Entry<K, V>> c, @CheckForNull Object o) {
3942    if (!(o instanceof Entry)) {
3943      return false;
3944    }
3945    return c.contains(unmodifiableEntry((Entry<?, ?>) o));
3946  }
3947
3948  /**
3949   * Implements {@code Collection.remove} safely for forwarding collections of map entries. If
3950   * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
3951   * protect against a possible nefarious equals method.
3952   *
3953   * <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection.
3954   *
3955   * @param c the delegate (unwrapped) collection of map entries
3956   * @param o the object to remove from {@code c}
3957   * @return {@code true} if {@code c} was changed
3958   */
3959  static <K extends @Nullable Object, V extends @Nullable Object> boolean removeEntryImpl(
3960      Collection<Entry<K, V>> c, @CheckForNull Object o) {
3961    if (!(o instanceof Entry)) {
3962      return false;
3963    }
3964    return c.remove(unmodifiableEntry((Entry<?, ?>) o));
3965  }
3966
3967  /** An implementation of {@link Map#equals}. */
3968  static boolean equalsImpl(Map<?, ?> map, @CheckForNull Object object) {
3969    if (map == object) {
3970      return true;
3971    } else if (object instanceof Map) {
3972      Map<?, ?> o = (Map<?, ?>) object;
3973      return map.entrySet().equals(o.entrySet());
3974    }
3975    return false;
3976  }
3977
3978  /** An implementation of {@link Map#toString}. */
3979  static String toStringImpl(Map<?, ?> map) {
3980    StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{');
3981    boolean first = true;
3982    for (Entry<?, ?> entry : map.entrySet()) {
3983      if (!first) {
3984        sb.append(", ");
3985      }
3986      first = false;
3987      sb.append(entry.getKey()).append('=').append(entry.getValue());
3988    }
3989    return sb.append('}').toString();
3990  }
3991
3992  /** An implementation of {@link Map#putAll}. */
3993  static <K extends @Nullable Object, V extends @Nullable Object> void putAllImpl(
3994      Map<K, V> self, Map<? extends K, ? extends V> map) {
3995    for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
3996      self.put(entry.getKey(), entry.getValue());
3997    }
3998  }
3999
4000  static class KeySet<K extends @Nullable Object, V extends @Nullable Object>
4001      extends Sets.ImprovedAbstractSet<K> {
4002    @Weak final Map<K, V> map;
4003
4004    KeySet(Map<K, V> map) {
4005      this.map = checkNotNull(map);
4006    }
4007
4008    Map<K, V> map() {
4009      return map;
4010    }
4011
4012    @Override
4013    public Iterator<K> iterator() {
4014      return keyIterator(map().entrySet().iterator());
4015    }
4016
4017    @Override
4018    public void forEach(Consumer<? super K> action) {
4019      checkNotNull(action);
4020      // avoids entry allocation for those maps that allocate entries on iteration
4021      map.forEach((k, v) -> action.accept(k));
4022    }
4023
4024    @Override
4025    public int size() {
4026      return map().size();
4027    }
4028
4029    @Override
4030    public boolean isEmpty() {
4031      return map().isEmpty();
4032    }
4033
4034    @Override
4035    public boolean contains(@CheckForNull Object o) {
4036      return map().containsKey(o);
4037    }
4038
4039    @Override
4040    public boolean remove(@CheckForNull Object o) {
4041      if (contains(o)) {
4042        map().remove(o);
4043        return true;
4044      }
4045      return false;
4046    }
4047
4048    @Override
4049    public void clear() {
4050      map().clear();
4051    }
4052  }
4053
4054  @CheckForNull
4055  static <K extends @Nullable Object> K keyOrNull(@CheckForNull Entry<K, ?> entry) {
4056    return (entry == null) ? null : entry.getKey();
4057  }
4058
4059  @CheckForNull
4060  static <V extends @Nullable Object> V valueOrNull(@CheckForNull Entry<?, V> entry) {
4061    return (entry == null) ? null : entry.getValue();
4062  }
4063
4064  static class SortedKeySet<K extends @Nullable Object, V extends @Nullable Object>
4065      extends KeySet<K, V> implements SortedSet<K> {
4066    SortedKeySet(SortedMap<K, V> map) {
4067      super(map);
4068    }
4069
4070    @Override
4071    SortedMap<K, V> map() {
4072      return (SortedMap<K, V>) super.map();
4073    }
4074
4075    @Override
4076    @CheckForNull
4077    public Comparator<? super K> comparator() {
4078      return map().comparator();
4079    }
4080
4081    @Override
4082    public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
4083      return new SortedKeySet<>(map().subMap(fromElement, toElement));
4084    }
4085
4086    @Override
4087    public SortedSet<K> headSet(@ParametricNullness K toElement) {
4088      return new SortedKeySet<>(map().headMap(toElement));
4089    }
4090
4091    @Override
4092    public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
4093      return new SortedKeySet<>(map().tailMap(fromElement));
4094    }
4095
4096    @Override
4097    @ParametricNullness
4098    public K first() {
4099      return map().firstKey();
4100    }
4101
4102    @Override
4103    @ParametricNullness
4104    public K last() {
4105      return map().lastKey();
4106    }
4107  }
4108
4109  @GwtIncompatible // NavigableMap
4110  static class NavigableKeySet<K extends @Nullable Object, V extends @Nullable Object>
4111      extends SortedKeySet<K, V> implements NavigableSet<K> {
4112    NavigableKeySet(NavigableMap<K, V> map) {
4113      super(map);
4114    }
4115
4116    @Override
4117    NavigableMap<K, V> map() {
4118      return (NavigableMap<K, V>) map;
4119    }
4120
4121    @Override
4122    @CheckForNull
4123    public K lower(@ParametricNullness K e) {
4124      return map().lowerKey(e);
4125    }
4126
4127    @Override
4128    @CheckForNull
4129    public K floor(@ParametricNullness K e) {
4130      return map().floorKey(e);
4131    }
4132
4133    @Override
4134    @CheckForNull
4135    public K ceiling(@ParametricNullness K e) {
4136      return map().ceilingKey(e);
4137    }
4138
4139    @Override
4140    @CheckForNull
4141    public K higher(@ParametricNullness K e) {
4142      return map().higherKey(e);
4143    }
4144
4145    @Override
4146    @CheckForNull
4147    public K pollFirst() {
4148      return keyOrNull(map().pollFirstEntry());
4149    }
4150
4151    @Override
4152    @CheckForNull
4153    public K pollLast() {
4154      return keyOrNull(map().pollLastEntry());
4155    }
4156
4157    @Override
4158    public NavigableSet<K> descendingSet() {
4159      return map().descendingKeySet();
4160    }
4161
4162    @Override
4163    public Iterator<K> descendingIterator() {
4164      return descendingSet().iterator();
4165    }
4166
4167    @Override
4168    public NavigableSet<K> subSet(
4169        @ParametricNullness K fromElement,
4170        boolean fromInclusive,
4171        @ParametricNullness K toElement,
4172        boolean toInclusive) {
4173      return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
4174    }
4175
4176    @Override
4177    public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
4178      return subSet(fromElement, true, toElement, false);
4179    }
4180
4181    @Override
4182    public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) {
4183      return map().headMap(toElement, inclusive).navigableKeySet();
4184    }
4185
4186    @Override
4187    public SortedSet<K> headSet(@ParametricNullness K toElement) {
4188      return headSet(toElement, false);
4189    }
4190
4191    @Override
4192    public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) {
4193      return map().tailMap(fromElement, inclusive).navigableKeySet();
4194    }
4195
4196    @Override
4197    public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
4198      return tailSet(fromElement, true);
4199    }
4200  }
4201
4202  static class Values<K extends @Nullable Object, V extends @Nullable Object>
4203      extends AbstractCollection<V> {
4204    @Weak final Map<K, V> map;
4205
4206    Values(Map<K, V> map) {
4207      this.map = checkNotNull(map);
4208    }
4209
4210    final Map<K, V> map() {
4211      return map;
4212    }
4213
4214    @Override
4215    public Iterator<V> iterator() {
4216      return valueIterator(map().entrySet().iterator());
4217    }
4218
4219    @Override
4220    public void forEach(Consumer<? super V> action) {
4221      checkNotNull(action);
4222      // avoids allocation of entries for those maps that generate fresh entries on iteration
4223      map.forEach((k, v) -> action.accept(v));
4224    }
4225
4226    @Override
4227    public boolean remove(@CheckForNull Object o) {
4228      try {
4229        return super.remove(o);
4230      } catch (UnsupportedOperationException e) {
4231        for (Entry<K, V> entry : map().entrySet()) {
4232          if (Objects.equal(o, entry.getValue())) {
4233            map().remove(entry.getKey());
4234            return true;
4235          }
4236        }
4237        return false;
4238      }
4239    }
4240
4241    @Override
4242    public boolean removeAll(Collection<?> c) {
4243      try {
4244        return super.removeAll(checkNotNull(c));
4245      } catch (UnsupportedOperationException e) {
4246        Set<K> toRemove = Sets.newHashSet();
4247        for (Entry<K, V> entry : map().entrySet()) {
4248          if (c.contains(entry.getValue())) {
4249            toRemove.add(entry.getKey());
4250          }
4251        }
4252        return map().keySet().removeAll(toRemove);
4253      }
4254    }
4255
4256    @Override
4257    public boolean retainAll(Collection<?> c) {
4258      try {
4259        return super.retainAll(checkNotNull(c));
4260      } catch (UnsupportedOperationException e) {
4261        Set<K> toRetain = Sets.newHashSet();
4262        for (Entry<K, V> entry : map().entrySet()) {
4263          if (c.contains(entry.getValue())) {
4264            toRetain.add(entry.getKey());
4265          }
4266        }
4267        return map().keySet().retainAll(toRetain);
4268      }
4269    }
4270
4271    @Override
4272    public int size() {
4273      return map().size();
4274    }
4275
4276    @Override
4277    public boolean isEmpty() {
4278      return map().isEmpty();
4279    }
4280
4281    @Override
4282    public boolean contains(@CheckForNull Object o) {
4283      return map().containsValue(o);
4284    }
4285
4286    @Override
4287    public void clear() {
4288      map().clear();
4289    }
4290  }
4291
4292  abstract static class EntrySet<K extends @Nullable Object, V extends @Nullable Object>
4293      extends Sets.ImprovedAbstractSet<Entry<K, V>> {
4294    abstract Map<K, V> map();
4295
4296    @Override
4297    public int size() {
4298      return map().size();
4299    }
4300
4301    @Override
4302    public void clear() {
4303      map().clear();
4304    }
4305
4306    @Override
4307    public boolean contains(@CheckForNull Object o) {
4308      if (o instanceof Entry) {
4309        Entry<?, ?> entry = (Entry<?, ?>) o;
4310        Object key = entry.getKey();
4311        V value = Maps.safeGet(map(), key);
4312        return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key));
4313      }
4314      return false;
4315    }
4316
4317    @Override
4318    public boolean isEmpty() {
4319      return map().isEmpty();
4320    }
4321
4322    @Override
4323    public boolean remove(@CheckForNull Object o) {
4324      /*
4325       * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
4326       * nullness checker.
4327       */
4328      if (contains(o) && o instanceof Entry) {
4329        Entry<?, ?> entry = (Entry<?, ?>) o;
4330        return map().keySet().remove(entry.getKey());
4331      }
4332      return false;
4333    }
4334
4335    @Override
4336    public boolean removeAll(Collection<?> c) {
4337      try {
4338        return super.removeAll(checkNotNull(c));
4339      } catch (UnsupportedOperationException e) {
4340        // if the iterators don't support remove
4341        return Sets.removeAllImpl(this, c.iterator());
4342      }
4343    }
4344
4345    @Override
4346    public boolean retainAll(Collection<?> c) {
4347      try {
4348        return super.retainAll(checkNotNull(c));
4349      } catch (UnsupportedOperationException e) {
4350        // if the iterators don't support remove
4351        Set<@Nullable Object> keys = Sets.newHashSetWithExpectedSize(c.size());
4352        for (Object o : c) {
4353          /*
4354           * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
4355           * nullness checker.
4356           */
4357          if (contains(o) && o instanceof Entry) {
4358            Entry<?, ?> entry = (Entry<?, ?>) o;
4359            keys.add(entry.getKey());
4360          }
4361        }
4362        return map().keySet().retainAll(keys);
4363      }
4364    }
4365  }
4366
4367  @GwtIncompatible // NavigableMap
4368  abstract static class DescendingMap<K extends @Nullable Object, V extends @Nullable Object>
4369      extends ForwardingMap<K, V> implements NavigableMap<K, V> {
4370
4371    abstract NavigableMap<K, V> forward();
4372
4373    @Override
4374    protected final Map<K, V> delegate() {
4375      return forward();
4376    }
4377
4378    @LazyInit @CheckForNull private transient Comparator<? super K> comparator;
4379
4380    @SuppressWarnings("unchecked")
4381    @Override
4382    public Comparator<? super K> comparator() {
4383      Comparator<? super K> result = comparator;
4384      if (result == null) {
4385        Comparator<? super K> forwardCmp = forward().comparator();
4386        if (forwardCmp == null) {
4387          forwardCmp = (Comparator) Ordering.natural();
4388        }
4389        result = comparator = reverse(forwardCmp);
4390      }
4391      return result;
4392    }
4393
4394    // If we inline this, we get a javac error.
4395    private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
4396      return Ordering.from(forward).reverse();
4397    }
4398
4399    @Override
4400    @ParametricNullness
4401    public K firstKey() {
4402      return forward().lastKey();
4403    }
4404
4405    @Override
4406    @ParametricNullness
4407    public K lastKey() {
4408      return forward().firstKey();
4409    }
4410
4411    @Override
4412    @CheckForNull
4413    public Entry<K, V> lowerEntry(@ParametricNullness K key) {
4414      return forward().higherEntry(key);
4415    }
4416
4417    @Override
4418    @CheckForNull
4419    public K lowerKey(@ParametricNullness K key) {
4420      return forward().higherKey(key);
4421    }
4422
4423    @Override
4424    @CheckForNull
4425    public Entry<K, V> floorEntry(@ParametricNullness K key) {
4426      return forward().ceilingEntry(key);
4427    }
4428
4429    @Override
4430    @CheckForNull
4431    public K floorKey(@ParametricNullness K key) {
4432      return forward().ceilingKey(key);
4433    }
4434
4435    @Override
4436    @CheckForNull
4437    public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
4438      return forward().floorEntry(key);
4439    }
4440
4441    @Override
4442    @CheckForNull
4443    public K ceilingKey(@ParametricNullness K key) {
4444      return forward().floorKey(key);
4445    }
4446
4447    @Override
4448    @CheckForNull
4449    public Entry<K, V> higherEntry(@ParametricNullness K key) {
4450      return forward().lowerEntry(key);
4451    }
4452
4453    @Override
4454    @CheckForNull
4455    public K higherKey(@ParametricNullness K key) {
4456      return forward().lowerKey(key);
4457    }
4458
4459    @Override
4460    @CheckForNull
4461    public Entry<K, V> firstEntry() {
4462      return forward().lastEntry();
4463    }
4464
4465    @Override
4466    @CheckForNull
4467    public Entry<K, V> lastEntry() {
4468      return forward().firstEntry();
4469    }
4470
4471    @Override
4472    @CheckForNull
4473    public Entry<K, V> pollFirstEntry() {
4474      return forward().pollLastEntry();
4475    }
4476
4477    @Override
4478    @CheckForNull
4479    public Entry<K, V> pollLastEntry() {
4480      return forward().pollFirstEntry();
4481    }
4482
4483    @Override
4484    public NavigableMap<K, V> descendingMap() {
4485      return forward();
4486    }
4487
4488    @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
4489
4490    @Override
4491    public Set<Entry<K, V>> entrySet() {
4492      Set<Entry<K, V>> result = entrySet;
4493      return (result == null) ? entrySet = createEntrySet() : result;
4494    }
4495
4496    abstract Iterator<Entry<K, V>> entryIterator();
4497
4498    Set<Entry<K, V>> createEntrySet() {
4499      @WeakOuter
4500      class EntrySetImpl extends EntrySet<K, V> {
4501        @Override
4502        Map<K, V> map() {
4503          return DescendingMap.this;
4504        }
4505
4506        @Override
4507        public Iterator<Entry<K, V>> iterator() {
4508          return entryIterator();
4509        }
4510      }
4511      return new EntrySetImpl();
4512    }
4513
4514    @Override
4515    public Set<K> keySet() {
4516      return navigableKeySet();
4517    }
4518
4519    @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet;
4520
4521    @Override
4522    public NavigableSet<K> navigableKeySet() {
4523      NavigableSet<K> result = navigableKeySet;
4524      return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result;
4525    }
4526
4527    @Override
4528    public NavigableSet<K> descendingKeySet() {
4529      return forward().navigableKeySet();
4530    }
4531
4532    @Override
4533    public NavigableMap<K, V> subMap(
4534        @ParametricNullness K fromKey,
4535        boolean fromInclusive,
4536        @ParametricNullness K toKey,
4537        boolean toInclusive) {
4538      return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
4539    }
4540
4541    @Override
4542    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
4543      return subMap(fromKey, true, toKey, false);
4544    }
4545
4546    @Override
4547    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
4548      return forward().tailMap(toKey, inclusive).descendingMap();
4549    }
4550
4551    @Override
4552    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
4553      return headMap(toKey, false);
4554    }
4555
4556    @Override
4557    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
4558      return forward().headMap(fromKey, inclusive).descendingMap();
4559    }
4560
4561    @Override
4562    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
4563      return tailMap(fromKey, true);
4564    }
4565
4566    @Override
4567    public Collection<V> values() {
4568      return new Values<>(this);
4569    }
4570
4571    @Override
4572    public String toString() {
4573      return standardToString();
4574    }
4575  }
4576
4577  /** Returns a map from the ith element of list to i. */
4578  static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) {
4579    ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size());
4580    int i = 0;
4581    for (E e : list) {
4582      builder.put(e, i++);
4583    }
4584    return builder.buildOrThrow();
4585  }
4586
4587  /**
4588   * Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
4589   *
4590   * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link
4591   * NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link
4592   * NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object,
4593   * boolean) headMap()}) to actually construct the view. Consult these methods for a full
4594   * description of the returned view's behavior.
4595   *
4596   * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
4597   * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link
4598   * Comparator}, which can violate the natural ordering. Using this method (or in general using
4599   * {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior.
4600   *
4601   * @since 20.0
4602   */
4603  @GwtIncompatible // NavigableMap
4604  public static <K extends Comparable<? super K>, V extends @Nullable Object>
4605      NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
4606    if (map.comparator() != null
4607        && map.comparator() != Ordering.natural()
4608        && range.hasLowerBound()
4609        && range.hasUpperBound()) {
4610      checkArgument(
4611          map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
4612          "map is using a custom comparator which is inconsistent with the natural ordering.");
4613    }
4614    if (range.hasLowerBound() && range.hasUpperBound()) {
4615      return map.subMap(
4616          range.lowerEndpoint(),
4617          range.lowerBoundType() == BoundType.CLOSED,
4618          range.upperEndpoint(),
4619          range.upperBoundType() == BoundType.CLOSED);
4620    } else if (range.hasLowerBound()) {
4621      return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
4622    } else if (range.hasUpperBound()) {
4623      return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
4624    }
4625    return checkNotNull(map);
4626  }
4627}