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    /*
1741     * TODO(cpovirk): Uncomment the @NonNull annotations below once our JDK stubs and J2KT
1742     * emulations include them.
1743     */
1744    @Override
1745    @CheckForNull
1746    public V computeIfPresent(
1747        K key,
1748        BiFunction<? super K, ? super /*@NonNull*/ V, ? extends @Nullable V> remappingFunction) {
1749      throw new UnsupportedOperationException();
1750    }
1751
1752    @Override
1753    @CheckForNull
1754    public V compute(
1755        K key,
1756        BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
1757      throw new UnsupportedOperationException();
1758    }
1759
1760    @Override
1761    @CheckForNull
1762    public V merge(
1763        K key,
1764        /*@NonNull*/ V value,
1765        BiFunction<? super /*@NonNull*/ V, ? super /*@NonNull*/ V, ? extends @Nullable V>
1766            function) {
1767      throw new UnsupportedOperationException();
1768    }
1769
1770    @Override
1771    public BiMap<V, K> inverse() {
1772      BiMap<V, K> result = inverse;
1773      return (result == null)
1774          ? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this)
1775          : result;
1776    }
1777
1778    @Override
1779    public Set<V> values() {
1780      Set<V> result = values;
1781      return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result;
1782    }
1783
1784    private static final long serialVersionUID = 0;
1785  }
1786
1787  /**
1788   * Returns a view of a map where each value is transformed by a function. All other properties of
1789   * the map, such as iteration order, are left intact. For example, the code:
1790   *
1791   * <pre>{@code
1792   * Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9);
1793   * Function<Integer, Double> sqrt =
1794   *     new Function<Integer, Double>() {
1795   *       public Double apply(Integer in) {
1796   *         return Math.sqrt((int) in);
1797   *       }
1798   *     };
1799   * Map<String, Double> transformed = Maps.transformValues(map, sqrt);
1800   * System.out.println(transformed);
1801   * }</pre>
1802   *
1803   * ... prints {@code {a=2.0, b=3.0}}.
1804   *
1805   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1806   * removal operations, and these are reflected in the underlying map.
1807   *
1808   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1809   * that the function is capable of accepting null input. The transformed map might contain null
1810   * values, if the function sometimes gives a null result.
1811   *
1812   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1813   *
1814   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1815   * to be a view, but it means that the function will be applied many times for bulk operations
1816   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1817   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1818   * view, copy the returned map into a new map of your choosing.
1819   */
1820  public static <
1821          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1822      Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) {
1823    return transformEntries(fromMap, asEntryTransformer(function));
1824  }
1825
1826  /**
1827   * Returns a view of a sorted map where each value is transformed by a function. All other
1828   * properties of the map, such as iteration order, are left intact. For example, the code:
1829   *
1830   * <pre>{@code
1831   * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9);
1832   * Function<Integer, Double> sqrt =
1833   *     new Function<Integer, Double>() {
1834   *       public Double apply(Integer in) {
1835   *         return Math.sqrt((int) in);
1836   *       }
1837   *     };
1838   * SortedMap<String, Double> transformed =
1839   *      Maps.transformValues(map, sqrt);
1840   * System.out.println(transformed);
1841   * }</pre>
1842   *
1843   * ... prints {@code {a=2.0, b=3.0}}.
1844   *
1845   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1846   * removal operations, and these are reflected in the underlying map.
1847   *
1848   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1849   * that the function is capable of accepting null input. The transformed map might contain null
1850   * values, if the function sometimes gives a null result.
1851   *
1852   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1853   *
1854   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1855   * to be a view, but it means that the function will be applied many times for bulk operations
1856   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1857   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1858   * view, copy the returned map into a new map of your choosing.
1859   *
1860   * @since 11.0
1861   */
1862  public static <
1863          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1864      SortedMap<K, V2> transformValues(
1865          SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
1866    return transformEntries(fromMap, asEntryTransformer(function));
1867  }
1868
1869  /**
1870   * Returns a view of a navigable map where each value is transformed by a function. All other
1871   * properties of the map, such as iteration order, are left intact. For example, the code:
1872   *
1873   * <pre>{@code
1874   * NavigableMap<String, Integer> map = Maps.newTreeMap();
1875   * map.put("a", 4);
1876   * map.put("b", 9);
1877   * Function<Integer, Double> sqrt =
1878   *     new Function<Integer, Double>() {
1879   *       public Double apply(Integer in) {
1880   *         return Math.sqrt((int) in);
1881   *       }
1882   *     };
1883   * NavigableMap<String, Double> transformed =
1884   *      Maps.transformNavigableValues(map, sqrt);
1885   * System.out.println(transformed);
1886   * }</pre>
1887   *
1888   * ... prints {@code {a=2.0, b=3.0}}.
1889   *
1890   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1891   * removal operations, and these are reflected in the underlying map.
1892   *
1893   * <p>It's acceptable for the underlying map to contain null keys, and even null values provided
1894   * that the function is capable of accepting null input. The transformed map might contain null
1895   * values, if the function sometimes gives a null result.
1896   *
1897   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1898   *
1899   * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map
1900   * to be a view, but it means that the function will be applied many times for bulk operations
1901   * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code
1902   * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a
1903   * view, copy the returned map into a new map of your choosing.
1904   *
1905   * @since 13.0
1906   */
1907  @GwtIncompatible // NavigableMap
1908  public static <
1909          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1910      NavigableMap<K, V2> transformValues(
1911          NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
1912    return transformEntries(fromMap, asEntryTransformer(function));
1913  }
1914
1915  /**
1916   * Returns a view of a map whose values are derived from the original map's entries. In contrast
1917   * to {@link #transformValues}, this method's entry-transformation logic may depend on the key as
1918   * well as the value.
1919   *
1920   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
1921   * example, the code:
1922   *
1923   * <pre>{@code
1924   * Map<String, Boolean> options =
1925   *     ImmutableMap.of("verbose", true, "sort", false);
1926   * EntryTransformer<String, Boolean, String> flagPrefixer =
1927   *     new EntryTransformer<String, Boolean, String>() {
1928   *       public String transformEntry(String key, Boolean value) {
1929   *         return value ? key : "no" + key;
1930   *       }
1931   *     };
1932   * Map<String, String> transformed =
1933   *     Maps.transformEntries(options, flagPrefixer);
1934   * System.out.println(transformed);
1935   * }</pre>
1936   *
1937   * ... prints {@code {verbose=verbose, sort=nosort}}.
1938   *
1939   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1940   * removal operations, and these are reflected in the underlying map.
1941   *
1942   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
1943   * the transformer is capable of accepting null inputs. The transformed map might contain null
1944   * values if the transformer sometimes gives a null result.
1945   *
1946   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
1947   *
1948   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
1949   * map to be a view, but it means that the transformer will be applied many times for bulk
1950   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
1951   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
1952   * doesn't need to be a view, copy the returned map into a new map of your choosing.
1953   *
1954   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
1955   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
1956   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
1957   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
1958   * transformed map.
1959   *
1960   * @since 7.0
1961   */
1962  public static <
1963          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
1964      Map<K, V2> transformEntries(
1965          Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
1966    return new TransformedEntriesMap<>(fromMap, transformer);
1967  }
1968
1969  /**
1970   * Returns a view of a sorted map whose values are derived from the original sorted map's entries.
1971   * In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on
1972   * the key as well as the value.
1973   *
1974   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
1975   * example, the code:
1976   *
1977   * <pre>{@code
1978   * Map<String, Boolean> options =
1979   *     ImmutableSortedMap.of("verbose", true, "sort", false);
1980   * EntryTransformer<String, Boolean, String> flagPrefixer =
1981   *     new EntryTransformer<String, Boolean, String>() {
1982   *       public String transformEntry(String key, Boolean value) {
1983   *         return value ? key : "yes" + key;
1984   *       }
1985   *     };
1986   * SortedMap<String, String> transformed =
1987   *     Maps.transformEntries(options, flagPrefixer);
1988   * System.out.println(transformed);
1989   * }</pre>
1990   *
1991   * ... prints {@code {sort=yessort, verbose=verbose}}.
1992   *
1993   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
1994   * removal operations, and these are reflected in the underlying map.
1995   *
1996   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
1997   * the transformer is capable of accepting null inputs. The transformed map might contain null
1998   * values if the transformer sometimes gives a null result.
1999   *
2000   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
2001   *
2002   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
2003   * map to be a view, but it means that the transformer will be applied many times for bulk
2004   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
2005   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
2006   * doesn't need to be a view, copy the returned map into a new map of your choosing.
2007   *
2008   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
2009   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
2010   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
2011   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
2012   * transformed map.
2013   *
2014   * @since 11.0
2015   */
2016  public static <
2017          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2018      SortedMap<K, V2> transformEntries(
2019          SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2020    return new TransformedEntriesSortedMap<>(fromMap, transformer);
2021  }
2022
2023  /**
2024   * Returns a view of a navigable map whose values are derived from the original navigable map's
2025   * entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may
2026   * depend on the key as well as the value.
2027   *
2028   * <p>All other properties of the transformed map, such as iteration order, are left intact. For
2029   * example, the code:
2030   *
2031   * <pre>{@code
2032   * NavigableMap<String, Boolean> options = Maps.newTreeMap();
2033   * options.put("verbose", false);
2034   * options.put("sort", true);
2035   * EntryTransformer<String, Boolean, String> flagPrefixer =
2036   *     new EntryTransformer<String, Boolean, String>() {
2037   *       public String transformEntry(String key, Boolean value) {
2038   *         return value ? key : ("yes" + key);
2039   *       }
2040   *     };
2041   * NavigableMap<String, String> transformed =
2042   *     LabsMaps.transformNavigableEntries(options, flagPrefixer);
2043   * System.out.println(transformed);
2044   * }</pre>
2045   *
2046   * ... prints {@code {sort=yessort, verbose=verbose}}.
2047   *
2048   * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports
2049   * removal operations, and these are reflected in the underlying map.
2050   *
2051   * <p>It's acceptable for the underlying map to contain null keys and null values provided that
2052   * the transformer is capable of accepting null inputs. The transformed map might contain null
2053   * values if the transformer sometimes gives a null result.
2054   *
2055   * <p>The returned map is not thread-safe or serializable, even if the underlying map is.
2056   *
2057   * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned
2058   * map to be a view, but it means that the transformer will be applied many times for bulk
2059   * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform
2060   * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map
2061   * doesn't need to be a view, copy the returned map into a new map of your choosing.
2062   *
2063   * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code
2064   * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of
2065   * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as
2066   * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the
2067   * transformed map.
2068   *
2069   * @since 13.0
2070   */
2071  @GwtIncompatible // NavigableMap
2072  public static <
2073          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2074      NavigableMap<K, V2> transformEntries(
2075          NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2076    return new TransformedEntriesNavigableMap<>(fromMap, transformer);
2077  }
2078
2079  /**
2080   * A transformation of the value of a key-value pair, using both key and value as inputs. To apply
2081   * the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}.
2082   *
2083   * @param <K> the key type of the input and output entries
2084   * @param <V1> the value type of the input entry
2085   * @param <V2> the value type of the output entry
2086   * @since 7.0
2087   */
2088  @FunctionalInterface
2089  public interface EntryTransformer<
2090      K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> {
2091    /**
2092     * Determines an output value based on a key-value pair. This method is <i>generally
2093     * expected</i>, but not absolutely required, to have the following properties:
2094     *
2095     * <ul>
2096     *   <li>Its execution does not cause any observable side effects.
2097     *   <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal
2098     *       Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that
2099     *       {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}.
2100     * </ul>
2101     *
2102     * @throws NullPointerException if the key or value is null and this transformer does not accept
2103     *     null arguments
2104     */
2105    @ParametricNullness
2106    V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value);
2107  }
2108
2109  /** Views a function as an entry transformer that ignores the entry key. */
2110  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2111      EntryTransformer<K, V1, V2> asEntryTransformer(final Function<? super V1, V2> function) {
2112    checkNotNull(function);
2113    return new EntryTransformer<K, V1, V2>() {
2114      @Override
2115      @ParametricNullness
2116      public V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value) {
2117        return function.apply(value);
2118      }
2119    };
2120  }
2121
2122  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2123      Function<V1, V2> asValueToValueFunction(
2124          final EntryTransformer<? super K, V1, V2> transformer, @ParametricNullness final K key) {
2125    checkNotNull(transformer);
2126    return new Function<V1, V2>() {
2127      @Override
2128      @ParametricNullness
2129      public V2 apply(@ParametricNullness V1 v1) {
2130        return transformer.transformEntry(key, v1);
2131      }
2132    };
2133  }
2134
2135  /** Views an entry transformer as a function from {@code Entry} to values. */
2136  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2137      Function<Entry<K, V1>, V2> asEntryToValueFunction(
2138          final EntryTransformer<? super K, ? super V1, V2> transformer) {
2139    checkNotNull(transformer);
2140    return new Function<Entry<K, V1>, V2>() {
2141      @Override
2142      @ParametricNullness
2143      public V2 apply(Entry<K, V1> entry) {
2144        return transformer.transformEntry(entry.getKey(), entry.getValue());
2145      }
2146    };
2147  }
2148
2149  /** Returns a view of an entry transformed by the specified transformer. */
2150  static <V2 extends @Nullable Object, K extends @Nullable Object, V1 extends @Nullable Object>
2151      Entry<K, V2> transformEntry(
2152          final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) {
2153    checkNotNull(transformer);
2154    checkNotNull(entry);
2155    return new AbstractMapEntry<K, V2>() {
2156      @Override
2157      @ParametricNullness
2158      public K getKey() {
2159        return entry.getKey();
2160      }
2161
2162      @Override
2163      @ParametricNullness
2164      public V2 getValue() {
2165        return transformer.transformEntry(entry.getKey(), entry.getValue());
2166      }
2167    };
2168  }
2169
2170  /** Views an entry transformer as a function from entries to entries. */
2171  static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2172      Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction(
2173          final EntryTransformer<? super K, ? super V1, V2> transformer) {
2174    checkNotNull(transformer);
2175    return new Function<Entry<K, V1>, Entry<K, V2>>() {
2176      @Override
2177      public Entry<K, V2> apply(final Entry<K, V1> entry) {
2178        return transformEntry(transformer, entry);
2179      }
2180    };
2181  }
2182
2183  static class TransformedEntriesMap<
2184          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2185      extends IteratorBasedAbstractMap<K, V2> {
2186    final Map<K, V1> fromMap;
2187    final EntryTransformer<? super K, ? super V1, V2> transformer;
2188
2189    TransformedEntriesMap(
2190        Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2191      this.fromMap = checkNotNull(fromMap);
2192      this.transformer = checkNotNull(transformer);
2193    }
2194
2195    @Override
2196    public int size() {
2197      return fromMap.size();
2198    }
2199
2200    @Override
2201    public boolean containsKey(@CheckForNull Object key) {
2202      return fromMap.containsKey(key);
2203    }
2204
2205    @Override
2206    @CheckForNull
2207    public V2 get(@CheckForNull Object key) {
2208      return getOrDefault(key, null);
2209    }
2210
2211    // safe as long as the user followed the <b>Warning</b> in the javadoc
2212    @SuppressWarnings("unchecked")
2213    @Override
2214    @CheckForNull
2215    public V2 getOrDefault(@CheckForNull Object key, @CheckForNull V2 defaultValue) {
2216      V1 value = fromMap.get(key);
2217      if (value != null || fromMap.containsKey(key)) {
2218        // The cast is safe because of the containsKey check.
2219        return transformer.transformEntry((K) key, uncheckedCastNullableTToT(value));
2220      }
2221      return defaultValue;
2222    }
2223
2224    // safe as long as the user followed the <b>Warning</b> in the javadoc
2225    @SuppressWarnings("unchecked")
2226    @Override
2227    @CheckForNull
2228    public V2 remove(@CheckForNull Object key) {
2229      return fromMap.containsKey(key)
2230          // The cast is safe because of the containsKey check.
2231          ? transformer.transformEntry((K) key, uncheckedCastNullableTToT(fromMap.remove(key)))
2232          : null;
2233    }
2234
2235    @Override
2236    public void clear() {
2237      fromMap.clear();
2238    }
2239
2240    @Override
2241    public Set<K> keySet() {
2242      return fromMap.keySet();
2243    }
2244
2245    @Override
2246    Iterator<Entry<K, V2>> entryIterator() {
2247      return Iterators.transform(
2248          fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
2249    }
2250
2251    @Override
2252    Spliterator<Entry<K, V2>> entrySpliterator() {
2253      return CollectSpliterators.map(
2254          fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer));
2255    }
2256
2257    @Override
2258    public void forEach(BiConsumer<? super K, ? super V2> action) {
2259      checkNotNull(action);
2260      // avoids creating new Entry<K, V2> objects
2261      fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1)));
2262    }
2263
2264    @Override
2265    public Collection<V2> values() {
2266      return new Values<>(this);
2267    }
2268  }
2269
2270  static class TransformedEntriesSortedMap<
2271          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2272      extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> {
2273
2274    protected SortedMap<K, V1> fromMap() {
2275      return (SortedMap<K, V1>) fromMap;
2276    }
2277
2278    TransformedEntriesSortedMap(
2279        SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2280      super(fromMap, transformer);
2281    }
2282
2283    @Override
2284    @CheckForNull
2285    public Comparator<? super K> comparator() {
2286      return fromMap().comparator();
2287    }
2288
2289    @Override
2290    @ParametricNullness
2291    public K firstKey() {
2292      return fromMap().firstKey();
2293    }
2294
2295    @Override
2296    public SortedMap<K, V2> headMap(@ParametricNullness K toKey) {
2297      return transformEntries(fromMap().headMap(toKey), transformer);
2298    }
2299
2300    @Override
2301    @ParametricNullness
2302    public K lastKey() {
2303      return fromMap().lastKey();
2304    }
2305
2306    @Override
2307    public SortedMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
2308      return transformEntries(fromMap().subMap(fromKey, toKey), transformer);
2309    }
2310
2311    @Override
2312    public SortedMap<K, V2> tailMap(@ParametricNullness K fromKey) {
2313      return transformEntries(fromMap().tailMap(fromKey), transformer);
2314    }
2315  }
2316
2317  @GwtIncompatible // NavigableMap
2318  private static class TransformedEntriesNavigableMap<
2319          K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object>
2320      extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> {
2321
2322    TransformedEntriesNavigableMap(
2323        NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) {
2324      super(fromMap, transformer);
2325    }
2326
2327    @Override
2328    @CheckForNull
2329    public Entry<K, V2> ceilingEntry(@ParametricNullness K key) {
2330      return transformEntry(fromMap().ceilingEntry(key));
2331    }
2332
2333    @Override
2334    @CheckForNull
2335    public K ceilingKey(@ParametricNullness K key) {
2336      return fromMap().ceilingKey(key);
2337    }
2338
2339    @Override
2340    public NavigableSet<K> descendingKeySet() {
2341      return fromMap().descendingKeySet();
2342    }
2343
2344    @Override
2345    public NavigableMap<K, V2> descendingMap() {
2346      return transformEntries(fromMap().descendingMap(), transformer);
2347    }
2348
2349    @Override
2350    @CheckForNull
2351    public Entry<K, V2> firstEntry() {
2352      return transformEntry(fromMap().firstEntry());
2353    }
2354
2355    @Override
2356    @CheckForNull
2357    public Entry<K, V2> floorEntry(@ParametricNullness K key) {
2358      return transformEntry(fromMap().floorEntry(key));
2359    }
2360
2361    @Override
2362    @CheckForNull
2363    public K floorKey(@ParametricNullness K key) {
2364      return fromMap().floorKey(key);
2365    }
2366
2367    @Override
2368    public NavigableMap<K, V2> headMap(@ParametricNullness K toKey) {
2369      return headMap(toKey, false);
2370    }
2371
2372    @Override
2373    public NavigableMap<K, V2> headMap(@ParametricNullness K toKey, boolean inclusive) {
2374      return transformEntries(fromMap().headMap(toKey, inclusive), transformer);
2375    }
2376
2377    @Override
2378    @CheckForNull
2379    public Entry<K, V2> higherEntry(@ParametricNullness K key) {
2380      return transformEntry(fromMap().higherEntry(key));
2381    }
2382
2383    @Override
2384    @CheckForNull
2385    public K higherKey(@ParametricNullness K key) {
2386      return fromMap().higherKey(key);
2387    }
2388
2389    @Override
2390    @CheckForNull
2391    public Entry<K, V2> lastEntry() {
2392      return transformEntry(fromMap().lastEntry());
2393    }
2394
2395    @Override
2396    @CheckForNull
2397    public Entry<K, V2> lowerEntry(@ParametricNullness K key) {
2398      return transformEntry(fromMap().lowerEntry(key));
2399    }
2400
2401    @Override
2402    @CheckForNull
2403    public K lowerKey(@ParametricNullness K key) {
2404      return fromMap().lowerKey(key);
2405    }
2406
2407    @Override
2408    public NavigableSet<K> navigableKeySet() {
2409      return fromMap().navigableKeySet();
2410    }
2411
2412    @Override
2413    @CheckForNull
2414    public Entry<K, V2> pollFirstEntry() {
2415      return transformEntry(fromMap().pollFirstEntry());
2416    }
2417
2418    @Override
2419    @CheckForNull
2420    public Entry<K, V2> pollLastEntry() {
2421      return transformEntry(fromMap().pollLastEntry());
2422    }
2423
2424    @Override
2425    public NavigableMap<K, V2> subMap(
2426        @ParametricNullness K fromKey,
2427        boolean fromInclusive,
2428        @ParametricNullness K toKey,
2429        boolean toInclusive) {
2430      return transformEntries(
2431          fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer);
2432    }
2433
2434    @Override
2435    public NavigableMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
2436      return subMap(fromKey, true, toKey, false);
2437    }
2438
2439    @Override
2440    public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey) {
2441      return tailMap(fromKey, true);
2442    }
2443
2444    @Override
2445    public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
2446      return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer);
2447    }
2448
2449    @CheckForNull
2450    private Entry<K, V2> transformEntry(@CheckForNull Entry<K, V1> entry) {
2451      return (entry == null) ? null : Maps.transformEntry(transformer, entry);
2452    }
2453
2454    @Override
2455    protected NavigableMap<K, V1> fromMap() {
2456      return (NavigableMap<K, V1>) super.fromMap();
2457    }
2458  }
2459
2460  static <K extends @Nullable Object> Predicate<Entry<K, ?>> keyPredicateOnEntries(
2461      Predicate<? super K> keyPredicate) {
2462    return compose(keyPredicate, Maps.<K>keyFunction());
2463  }
2464
2465  static <V extends @Nullable Object> Predicate<Entry<?, V>> valuePredicateOnEntries(
2466      Predicate<? super V> valuePredicate) {
2467    return compose(valuePredicate, Maps.<V>valueFunction());
2468  }
2469
2470  /**
2471   * Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The
2472   * returned map is a live view of {@code unfiltered}; changes to one affect the other.
2473   *
2474   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2475   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2476   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2477   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2478   *
2479   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2480   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2481   * map.
2482   *
2483   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2484   *
2485   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2486   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2487   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2488   *
2489   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2490   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2491   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2492   */
2493  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterKeys(
2494      Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2495    checkNotNull(keyPredicate);
2496    Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate);
2497    return (unfiltered instanceof AbstractFilteredMap)
2498        ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
2499        : new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate);
2500  }
2501
2502  /**
2503   * Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a
2504   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2505   * other.
2506   *
2507   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2508   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2509   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2510   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2511   *
2512   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2513   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2514   * map.
2515   *
2516   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2517   *
2518   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2519   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2520   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2521   *
2522   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2523   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2524   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2525   *
2526   * @since 11.0
2527   */
2528  public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterKeys(
2529      SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2530    // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
2531    // performance.
2532    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2533  }
2534
2535  /**
2536   * Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a
2537   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2538   * other.
2539   *
2540   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2541   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2542   * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and
2543   * {@code putAll()} methods throw an {@link IllegalArgumentException}.
2544   *
2545   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2546   * or its views, only mappings whose keys satisfy the filter will be removed from the underlying
2547   * map.
2548   *
2549   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2550   *
2551   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2552   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2553   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2554   *
2555   * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at
2556   * {@link Predicate#apply}. Do not provide a predicate such as {@code
2557   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2558   *
2559   * @since 14.0
2560   */
2561  @GwtIncompatible // NavigableMap
2562  public static <K extends @Nullable Object, V extends @Nullable Object>
2563      NavigableMap<K, V> filterKeys(
2564          NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2565    // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better
2566    // performance.
2567    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2568  }
2569
2570  /**
2571   * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate.
2572   * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2573   *
2574   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2575   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2576   * and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()},
2577   * {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}.
2578   *
2579   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2580   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2581   * bimap.
2582   *
2583   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2584   *
2585   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in
2586   * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
2587   * needed, it may be faster to copy the filtered bimap and use the copy.
2588   *
2589   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2590   * at {@link Predicate#apply}.
2591   *
2592   * @since 14.0
2593   */
2594  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterKeys(
2595      BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) {
2596    checkNotNull(keyPredicate);
2597    return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate));
2598  }
2599
2600  /**
2601   * Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate.
2602   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2603   *
2604   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2605   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2606   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2607   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2608   *
2609   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2610   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2611   * map.
2612   *
2613   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2614   *
2615   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2616   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2617   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2618   *
2619   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2620   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2621   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2622   */
2623  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterValues(
2624      Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2625    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2626  }
2627
2628  /**
2629   * Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a
2630   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2631   * other.
2632   *
2633   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2634   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2635   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2636   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2637   *
2638   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2639   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2640   * map.
2641   *
2642   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2643   *
2644   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2645   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2646   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2647   *
2648   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2649   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2650   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2651   *
2652   * @since 11.0
2653   */
2654  public static <K extends @Nullable Object, V extends @Nullable Object>
2655      SortedMap<K, V> filterValues(
2656          SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2657    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2658  }
2659
2660  /**
2661   * Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a
2662   * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the
2663   * other.
2664   *
2665   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2666   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2667   * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()},
2668   * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}.
2669   *
2670   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2671   * or its views, only mappings whose values satisfy the filter will be removed from the underlying
2672   * map.
2673   *
2674   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2675   *
2676   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2677   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2678   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2679   *
2680   * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented
2681   * at {@link Predicate#apply}. Do not provide a predicate such as {@code
2682   * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals.
2683   *
2684   * @since 14.0
2685   */
2686  @GwtIncompatible // NavigableMap
2687  public static <K extends @Nullable Object, V extends @Nullable Object>
2688      NavigableMap<K, V> filterValues(
2689          NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2690    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2691  }
2692
2693  /**
2694   * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate.
2695   * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2696   *
2697   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2698   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2699   * and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code
2700   * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
2701   * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method
2702   * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the
2703   * predicate.
2704   *
2705   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2706   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2707   * bimap.
2708   *
2709   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2710   *
2711   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in
2712   * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i>
2713   * needed, it may be faster to copy the filtered bimap and use the copy.
2714   *
2715   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2716   * at {@link Predicate#apply}.
2717   *
2718   * @since 14.0
2719   */
2720  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterValues(
2721      BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) {
2722    return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate));
2723  }
2724
2725  /**
2726   * Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The
2727   * returned map is a live view of {@code unfiltered}; changes to one affect the other.
2728   *
2729   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2730   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2731   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2732   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2733   * map's entries have a {@link Entry#setValue} method that throws an {@link
2734   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2735   * predicate.
2736   *
2737   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2738   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2739   *
2740   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2741   *
2742   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2743   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2744   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2745   *
2746   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2747   * at {@link Predicate#apply}.
2748   */
2749  public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterEntries(
2750      Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2751    checkNotNull(entryPredicate);
2752    return (unfiltered instanceof AbstractFilteredMap)
2753        ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate)
2754        : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2755  }
2756
2757  /**
2758   * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
2759   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2760   *
2761   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2762   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2763   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2764   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2765   * map's entries have a {@link Entry#setValue} method that throws an {@link
2766   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2767   * predicate.
2768   *
2769   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2770   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2771   *
2772   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2773   *
2774   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2775   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2776   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2777   *
2778   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2779   * at {@link Predicate#apply}.
2780   *
2781   * @since 11.0
2782   */
2783  public static <K extends @Nullable Object, V extends @Nullable Object>
2784      SortedMap<K, V> filterEntries(
2785          SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2786    checkNotNull(entryPredicate);
2787    return (unfiltered instanceof FilteredEntrySortedMap)
2788        ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate)
2789        : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2790  }
2791
2792  /**
2793   * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate.
2794   * The returned map is a live view of {@code unfiltered}; changes to one affect the other.
2795   *
2796   * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2797   * iterators that don't support {@code remove()}, but all other methods are supported by the map
2798   * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code
2799   * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the
2800   * map's entries have a {@link Entry#setValue} method that throws an {@link
2801   * IllegalArgumentException} when the existing key and the provided value don't satisfy the
2802   * predicate.
2803   *
2804   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map
2805   * or its views, only mappings that satisfy the filter will be removed from the underlying map.
2806   *
2807   * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is.
2808   *
2809   * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value
2810   * mapping in the underlying map and determine which satisfy the filter. When a live view is
2811   * <i>not</i> needed, it may be faster to copy the filtered map and use the copy.
2812   *
2813   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented
2814   * at {@link Predicate#apply}.
2815   *
2816   * @since 14.0
2817   */
2818  @GwtIncompatible // NavigableMap
2819  public static <K extends @Nullable Object, V extends @Nullable Object>
2820      NavigableMap<K, V> filterEntries(
2821          NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2822    checkNotNull(entryPredicate);
2823    return (unfiltered instanceof FilteredEntryNavigableMap)
2824        ? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate)
2825        : new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate);
2826  }
2827
2828  /**
2829   * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The
2830   * returned bimap is a live view of {@code unfiltered}; changes to one affect the other.
2831   *
2832   * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have
2833   * iterators that don't support {@code remove()}, but all other methods are supported by the bimap
2834   * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's
2835   * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link
2836   * IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method
2837   * that throws an {@link IllegalArgumentException} when the existing key and the provided value
2838   * don't satisfy the predicate.
2839   *
2840   * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered
2841   * bimap or its views, only mappings that satisfy the filter will be removed from the underlying
2842   * bimap.
2843   *
2844   * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is.
2845   *
2846   * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value
2847   * mapping in the underlying bimap and determine which satisfy the filter. When a live view is
2848   * <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy.
2849   *
2850   * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented
2851   * at {@link Predicate#apply}.
2852   *
2853   * @since 14.0
2854   */
2855  public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterEntries(
2856      BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
2857    checkNotNull(unfiltered);
2858    checkNotNull(entryPredicate);
2859    return (unfiltered instanceof FilteredEntryBiMap)
2860        ? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate)
2861        : new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate);
2862  }
2863
2864  /**
2865   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2866   * map.
2867   */
2868  private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterFiltered(
2869      AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2870    return new FilteredEntryMap<>(
2871        map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate));
2872  }
2873
2874  /**
2875   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2876   * sorted map.
2877   */
2878  private static <K extends @Nullable Object, V extends @Nullable Object>
2879      SortedMap<K, V> filterFiltered(
2880          FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2881    Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
2882    return new FilteredEntrySortedMap<>(map.sortedMap(), predicate);
2883  }
2884
2885  /**
2886   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2887   * navigable map.
2888   */
2889  @GwtIncompatible // NavigableMap
2890  private static <K extends @Nullable Object, V extends @Nullable Object>
2891      NavigableMap<K, V> filterFiltered(
2892          FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2893    Predicate<Entry<K, V>> predicate =
2894        Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate);
2895    return new FilteredEntryNavigableMap<>(map.unfiltered, predicate);
2896  }
2897
2898  /**
2899   * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered
2900   * map.
2901   */
2902  private static <K extends @Nullable Object, V extends @Nullable Object>
2903      BiMap<K, V> filterFiltered(
2904          FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) {
2905    Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate);
2906    return new FilteredEntryBiMap<>(map.unfiltered(), predicate);
2907  }
2908
2909  private abstract static class AbstractFilteredMap<
2910          K extends @Nullable Object, V extends @Nullable Object>
2911      extends ViewCachingAbstractMap<K, V> {
2912    final Map<K, V> unfiltered;
2913    final Predicate<? super Entry<K, V>> predicate;
2914
2915    AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
2916      this.unfiltered = unfiltered;
2917      this.predicate = predicate;
2918    }
2919
2920    boolean apply(@CheckForNull Object key, @ParametricNullness V value) {
2921      // This method is called only when the key is in the map (or about to be added to the map),
2922      // implying that key is a K.
2923      @SuppressWarnings({"unchecked", "nullness"})
2924      K k = (K) key;
2925      return predicate.apply(Maps.immutableEntry(k, value));
2926    }
2927
2928    @Override
2929    @CheckForNull
2930    public V put(@ParametricNullness K key, @ParametricNullness V value) {
2931      checkArgument(apply(key, value));
2932      return unfiltered.put(key, value);
2933    }
2934
2935    @Override
2936    public void putAll(Map<? extends K, ? extends V> map) {
2937      for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
2938        checkArgument(apply(entry.getKey(), entry.getValue()));
2939      }
2940      unfiltered.putAll(map);
2941    }
2942
2943    @Override
2944    public boolean containsKey(@CheckForNull Object key) {
2945      return unfiltered.containsKey(key) && apply(key, unfiltered.get(key));
2946    }
2947
2948    @Override
2949    @CheckForNull
2950    public V get(@CheckForNull Object key) {
2951      V value = unfiltered.get(key);
2952      return ((value != null) && apply(key, value)) ? value : null;
2953    }
2954
2955    @Override
2956    public boolean isEmpty() {
2957      return entrySet().isEmpty();
2958    }
2959
2960    @Override
2961    @CheckForNull
2962    public V remove(@CheckForNull Object key) {
2963      return containsKey(key) ? unfiltered.remove(key) : null;
2964    }
2965
2966    @Override
2967    Collection<V> createValues() {
2968      return new FilteredMapValues<>(this, unfiltered, predicate);
2969    }
2970  }
2971
2972  private static final class FilteredMapValues<
2973          K extends @Nullable Object, V extends @Nullable Object>
2974      extends Maps.Values<K, V> {
2975    final Map<K, V> unfiltered;
2976    final Predicate<? super Entry<K, V>> predicate;
2977
2978    FilteredMapValues(
2979        Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) {
2980      super(filteredMap);
2981      this.unfiltered = unfiltered;
2982      this.predicate = predicate;
2983    }
2984
2985    @Override
2986    public boolean remove(@CheckForNull Object o) {
2987      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
2988      while (entryItr.hasNext()) {
2989        Entry<K, V> entry = entryItr.next();
2990        if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) {
2991          entryItr.remove();
2992          return true;
2993        }
2994      }
2995      return false;
2996    }
2997
2998    @Override
2999    public boolean removeAll(Collection<?> collection) {
3000      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
3001      boolean result = false;
3002      while (entryItr.hasNext()) {
3003        Entry<K, V> entry = entryItr.next();
3004        if (predicate.apply(entry) && collection.contains(entry.getValue())) {
3005          entryItr.remove();
3006          result = true;
3007        }
3008      }
3009      return result;
3010    }
3011
3012    @Override
3013    public boolean retainAll(Collection<?> collection) {
3014      Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator();
3015      boolean result = false;
3016      while (entryItr.hasNext()) {
3017        Entry<K, V> entry = entryItr.next();
3018        if (predicate.apply(entry) && !collection.contains(entry.getValue())) {
3019          entryItr.remove();
3020          result = true;
3021        }
3022      }
3023      return result;
3024    }
3025
3026    @Override
3027    public @Nullable Object[] toArray() {
3028      // creating an ArrayList so filtering happens once
3029      return Lists.newArrayList(iterator()).toArray();
3030    }
3031
3032    @Override
3033    @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
3034    public <T extends @Nullable Object> T[] toArray(T[] array) {
3035      return Lists.newArrayList(iterator()).toArray(array);
3036    }
3037  }
3038
3039  private static class FilteredKeyMap<K extends @Nullable Object, V extends @Nullable Object>
3040      extends AbstractFilteredMap<K, V> {
3041    final Predicate<? super K> keyPredicate;
3042
3043    FilteredKeyMap(
3044        Map<K, V> unfiltered,
3045        Predicate<? super K> keyPredicate,
3046        Predicate<? super Entry<K, V>> entryPredicate) {
3047      super(unfiltered, entryPredicate);
3048      this.keyPredicate = keyPredicate;
3049    }
3050
3051    @Override
3052    protected Set<Entry<K, V>> createEntrySet() {
3053      return Sets.filter(unfiltered.entrySet(), predicate);
3054    }
3055
3056    @Override
3057    Set<K> createKeySet() {
3058      return Sets.filter(unfiltered.keySet(), keyPredicate);
3059    }
3060
3061    // The cast is called only when the key is in the unfiltered map, implying
3062    // that key is a K.
3063    @Override
3064    @SuppressWarnings("unchecked")
3065    public boolean containsKey(@CheckForNull Object key) {
3066      return unfiltered.containsKey(key) && keyPredicate.apply((K) key);
3067    }
3068  }
3069
3070  static class FilteredEntryMap<K extends @Nullable Object, V extends @Nullable Object>
3071      extends AbstractFilteredMap<K, V> {
3072    /**
3073     * Entries in this set satisfy the predicate, but they don't validate the input to {@code
3074     * Entry.setValue()}.
3075     */
3076    final Set<Entry<K, V>> filteredEntrySet;
3077
3078    FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3079      super(unfiltered, entryPredicate);
3080      filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate);
3081    }
3082
3083    @Override
3084    protected Set<Entry<K, V>> createEntrySet() {
3085      return new EntrySet();
3086    }
3087
3088    @WeakOuter
3089    private class EntrySet extends ForwardingSet<Entry<K, V>> {
3090      @Override
3091      protected Set<Entry<K, V>> delegate() {
3092        return filteredEntrySet;
3093      }
3094
3095      @Override
3096      public Iterator<Entry<K, V>> iterator() {
3097        return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) {
3098          @Override
3099          Entry<K, V> transform(final Entry<K, V> entry) {
3100            return new ForwardingMapEntry<K, V>() {
3101              @Override
3102              protected Entry<K, V> delegate() {
3103                return entry;
3104              }
3105
3106              @Override
3107              @ParametricNullness
3108              public V setValue(@ParametricNullness V newValue) {
3109                checkArgument(apply(getKey(), newValue));
3110                return super.setValue(newValue);
3111              }
3112            };
3113          }
3114        };
3115      }
3116    }
3117
3118    @Override
3119    Set<K> createKeySet() {
3120      return new KeySet();
3121    }
3122
3123    static <K extends @Nullable Object, V extends @Nullable Object> boolean removeAllKeys(
3124        Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
3125      Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
3126      boolean result = false;
3127      while (entryItr.hasNext()) {
3128        Entry<K, V> entry = entryItr.next();
3129        if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) {
3130          entryItr.remove();
3131          result = true;
3132        }
3133      }
3134      return result;
3135    }
3136
3137    static <K extends @Nullable Object, V extends @Nullable Object> boolean retainAllKeys(
3138        Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) {
3139      Iterator<Entry<K, V>> entryItr = map.entrySet().iterator();
3140      boolean result = false;
3141      while (entryItr.hasNext()) {
3142        Entry<K, V> entry = entryItr.next();
3143        if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) {
3144          entryItr.remove();
3145          result = true;
3146        }
3147      }
3148      return result;
3149    }
3150
3151    @WeakOuter
3152    class KeySet extends Maps.KeySet<K, V> {
3153      KeySet() {
3154        super(FilteredEntryMap.this);
3155      }
3156
3157      @Override
3158      public boolean remove(@CheckForNull Object o) {
3159        if (containsKey(o)) {
3160          unfiltered.remove(o);
3161          return true;
3162        }
3163        return false;
3164      }
3165
3166      @Override
3167      public boolean removeAll(Collection<?> collection) {
3168        return removeAllKeys(unfiltered, predicate, collection);
3169      }
3170
3171      @Override
3172      public boolean retainAll(Collection<?> collection) {
3173        return retainAllKeys(unfiltered, predicate, collection);
3174      }
3175
3176      @Override
3177      public @Nullable Object[] toArray() {
3178        // creating an ArrayList so filtering happens once
3179        return Lists.newArrayList(iterator()).toArray();
3180      }
3181
3182      @Override
3183      @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations
3184      public <T extends @Nullable Object> T[] toArray(T[] array) {
3185        return Lists.newArrayList(iterator()).toArray(array);
3186      }
3187    }
3188  }
3189
3190  private static class FilteredEntrySortedMap<
3191          K extends @Nullable Object, V extends @Nullable Object>
3192      extends FilteredEntryMap<K, V> implements SortedMap<K, V> {
3193
3194    FilteredEntrySortedMap(
3195        SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3196      super(unfiltered, entryPredicate);
3197    }
3198
3199    SortedMap<K, V> sortedMap() {
3200      return (SortedMap<K, V>) unfiltered;
3201    }
3202
3203    @Override
3204    public SortedSet<K> keySet() {
3205      return (SortedSet<K>) super.keySet();
3206    }
3207
3208    @Override
3209    SortedSet<K> createKeySet() {
3210      return new SortedKeySet();
3211    }
3212
3213    @WeakOuter
3214    class SortedKeySet extends KeySet implements SortedSet<K> {
3215      @Override
3216      @CheckForNull
3217      public Comparator<? super K> comparator() {
3218        return sortedMap().comparator();
3219      }
3220
3221      @Override
3222      public SortedSet<K> subSet(
3223          @ParametricNullness K fromElement, @ParametricNullness K toElement) {
3224        return (SortedSet<K>) subMap(fromElement, toElement).keySet();
3225      }
3226
3227      @Override
3228      public SortedSet<K> headSet(@ParametricNullness K toElement) {
3229        return (SortedSet<K>) headMap(toElement).keySet();
3230      }
3231
3232      @Override
3233      public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
3234        return (SortedSet<K>) tailMap(fromElement).keySet();
3235      }
3236
3237      @Override
3238      @ParametricNullness
3239      public K first() {
3240        return firstKey();
3241      }
3242
3243      @Override
3244      @ParametricNullness
3245      public K last() {
3246        return lastKey();
3247      }
3248    }
3249
3250    @Override
3251    @CheckForNull
3252    public Comparator<? super K> comparator() {
3253      return sortedMap().comparator();
3254    }
3255
3256    @Override
3257    @ParametricNullness
3258    public K firstKey() {
3259      // correctly throws NoSuchElementException when filtered map is empty.
3260      return keySet().iterator().next();
3261    }
3262
3263    @Override
3264    @ParametricNullness
3265    public K lastKey() {
3266      SortedMap<K, V> headMap = sortedMap();
3267      while (true) {
3268        // correctly throws NoSuchElementException when filtered map is empty.
3269        K key = headMap.lastKey();
3270        // The cast is safe because the key is taken from the map.
3271        if (apply(key, uncheckedCastNullableTToT(unfiltered.get(key)))) {
3272          return key;
3273        }
3274        headMap = sortedMap().headMap(key);
3275      }
3276    }
3277
3278    @Override
3279    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
3280      return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate);
3281    }
3282
3283    @Override
3284    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
3285      return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate);
3286    }
3287
3288    @Override
3289    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
3290      return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate);
3291    }
3292  }
3293
3294  @GwtIncompatible // NavigableMap
3295  private static class FilteredEntryNavigableMap<
3296          K extends @Nullable Object, V extends @Nullable Object>
3297      extends AbstractNavigableMap<K, V> {
3298    /*
3299     * It's less code to extend AbstractNavigableMap and forward the filtering logic to
3300     * FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap
3301     * methods.
3302     */
3303
3304    private final NavigableMap<K, V> unfiltered;
3305    private final Predicate<? super Entry<K, V>> entryPredicate;
3306    private final Map<K, V> filteredDelegate;
3307
3308    FilteredEntryNavigableMap(
3309        NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) {
3310      this.unfiltered = checkNotNull(unfiltered);
3311      this.entryPredicate = entryPredicate;
3312      this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate);
3313    }
3314
3315    @Override
3316    @CheckForNull
3317    public Comparator<? super K> comparator() {
3318      return unfiltered.comparator();
3319    }
3320
3321    @Override
3322    public NavigableSet<K> navigableKeySet() {
3323      return new Maps.NavigableKeySet<K, V>(this) {
3324        @Override
3325        public boolean removeAll(Collection<?> collection) {
3326          return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection);
3327        }
3328
3329        @Override
3330        public boolean retainAll(Collection<?> collection) {
3331          return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection);
3332        }
3333      };
3334    }
3335
3336    @Override
3337    public Collection<V> values() {
3338      return new FilteredMapValues<>(this, unfiltered, entryPredicate);
3339    }
3340
3341    @Override
3342    Iterator<Entry<K, V>> entryIterator() {
3343      return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate);
3344    }
3345
3346    @Override
3347    Iterator<Entry<K, V>> descendingEntryIterator() {
3348      return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate);
3349    }
3350
3351    @Override
3352    public int size() {
3353      return filteredDelegate.size();
3354    }
3355
3356    @Override
3357    public boolean isEmpty() {
3358      return !Iterables.any(unfiltered.entrySet(), entryPredicate);
3359    }
3360
3361    @Override
3362    @CheckForNull
3363    public V get(@CheckForNull Object key) {
3364      return filteredDelegate.get(key);
3365    }
3366
3367    @Override
3368    public boolean containsKey(@CheckForNull Object key) {
3369      return filteredDelegate.containsKey(key);
3370    }
3371
3372    @Override
3373    @CheckForNull
3374    public V put(@ParametricNullness K key, @ParametricNullness V value) {
3375      return filteredDelegate.put(key, value);
3376    }
3377
3378    @Override
3379    @CheckForNull
3380    public V remove(@CheckForNull Object key) {
3381      return filteredDelegate.remove(key);
3382    }
3383
3384    @Override
3385    public void putAll(Map<? extends K, ? extends V> m) {
3386      filteredDelegate.putAll(m);
3387    }
3388
3389    @Override
3390    public void clear() {
3391      filteredDelegate.clear();
3392    }
3393
3394    @Override
3395    public Set<Entry<K, V>> entrySet() {
3396      return filteredDelegate.entrySet();
3397    }
3398
3399    @Override
3400    @CheckForNull
3401    public Entry<K, V> pollFirstEntry() {
3402      return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate);
3403    }
3404
3405    @Override
3406    @CheckForNull
3407    public Entry<K, V> pollLastEntry() {
3408      return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate);
3409    }
3410
3411    @Override
3412    public NavigableMap<K, V> descendingMap() {
3413      return filterEntries(unfiltered.descendingMap(), entryPredicate);
3414    }
3415
3416    @Override
3417    public NavigableMap<K, V> subMap(
3418        @ParametricNullness K fromKey,
3419        boolean fromInclusive,
3420        @ParametricNullness K toKey,
3421        boolean toInclusive) {
3422      return filterEntries(
3423          unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate);
3424    }
3425
3426    @Override
3427    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
3428      return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate);
3429    }
3430
3431    @Override
3432    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
3433      return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate);
3434    }
3435  }
3436
3437  static final class FilteredEntryBiMap<K extends @Nullable Object, V extends @Nullable Object>
3438      extends FilteredEntryMap<K, V> implements BiMap<K, V> {
3439    @RetainedWith private final BiMap<V, K> inverse;
3440
3441    private static <K extends @Nullable Object, V extends @Nullable Object>
3442        Predicate<Entry<V, K>> inversePredicate(
3443            final Predicate<? super Entry<K, V>> forwardPredicate) {
3444      return new Predicate<Entry<V, K>>() {
3445        @Override
3446        public boolean apply(Entry<V, K> input) {
3447          return forwardPredicate.apply(Maps.immutableEntry(input.getValue(), input.getKey()));
3448        }
3449      };
3450    }
3451
3452    FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) {
3453      super(delegate, predicate);
3454      this.inverse =
3455          new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this);
3456    }
3457
3458    private FilteredEntryBiMap(
3459        BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) {
3460      super(delegate, predicate);
3461      this.inverse = inverse;
3462    }
3463
3464    BiMap<K, V> unfiltered() {
3465      return (BiMap<K, V>) unfiltered;
3466    }
3467
3468    @Override
3469    @CheckForNull
3470    public V forcePut(@ParametricNullness K key, @ParametricNullness V value) {
3471      checkArgument(apply(key, value));
3472      return unfiltered().forcePut(key, value);
3473    }
3474
3475    @Override
3476    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3477      unfiltered()
3478          .replaceAll(
3479              (key, value) ->
3480                  predicate.apply(Maps.immutableEntry(key, value))
3481                      ? function.apply(key, value)
3482                      : value);
3483    }
3484
3485    @Override
3486    public BiMap<V, K> inverse() {
3487      return inverse;
3488    }
3489
3490    @Override
3491    public Set<V> values() {
3492      return inverse.keySet();
3493    }
3494  }
3495
3496  /**
3497   * Returns an unmodifiable view of the specified navigable map. Query operations on the returned
3498   * map read through to the specified map, and attempts to modify the returned map, whether direct
3499   * or via its views, result in an {@code UnsupportedOperationException}.
3500   *
3501   * <p>The returned navigable map will be serializable if the specified navigable map is
3502   * serializable.
3503   *
3504   * <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K,
3505   * V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code
3506   * comparator()} method might return a {@code Comparator<? extends K>}, which works only on a
3507   * particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which
3508   * must work on any type of {@code K}.
3509   *
3510   * @param map the navigable map for which an unmodifiable view is to be returned
3511   * @return an unmodifiable view of the specified navigable map
3512   * @since 12.0
3513   */
3514  @GwtIncompatible // NavigableMap
3515  public static <K extends @Nullable Object, V extends @Nullable Object>
3516      NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) {
3517    checkNotNull(map);
3518    if (map instanceof UnmodifiableNavigableMap) {
3519      @SuppressWarnings("unchecked") // covariant
3520      NavigableMap<K, V> result = (NavigableMap<K, V>) map;
3521      return result;
3522    } else {
3523      return new UnmodifiableNavigableMap<>(map);
3524    }
3525  }
3526
3527  @CheckForNull
3528  private static <K extends @Nullable Object, V extends @Nullable Object>
3529      Entry<K, V> unmodifiableOrNull(@CheckForNull Entry<K, ? extends V> entry) {
3530    return (entry == null) ? null : Maps.unmodifiableEntry(entry);
3531  }
3532
3533  @GwtIncompatible // NavigableMap
3534  static class UnmodifiableNavigableMap<K extends @Nullable Object, V extends @Nullable Object>
3535      extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable {
3536    private final NavigableMap<K, ? extends V> delegate;
3537
3538    UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) {
3539      this.delegate = delegate;
3540    }
3541
3542    UnmodifiableNavigableMap(
3543        NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) {
3544      this.delegate = delegate;
3545      this.descendingMap = descendingMap;
3546    }
3547
3548    @Override
3549    protected SortedMap<K, V> delegate() {
3550      return Collections.unmodifiableSortedMap(delegate);
3551    }
3552
3553    @Override
3554    @CheckForNull
3555    public Entry<K, V> lowerEntry(@ParametricNullness K key) {
3556      return unmodifiableOrNull(delegate.lowerEntry(key));
3557    }
3558
3559    @Override
3560    @CheckForNull
3561    public K lowerKey(@ParametricNullness K key) {
3562      return delegate.lowerKey(key);
3563    }
3564
3565    @Override
3566    @CheckForNull
3567    public Entry<K, V> floorEntry(@ParametricNullness K key) {
3568      return unmodifiableOrNull(delegate.floorEntry(key));
3569    }
3570
3571    @Override
3572    @CheckForNull
3573    public K floorKey(@ParametricNullness K key) {
3574      return delegate.floorKey(key);
3575    }
3576
3577    @Override
3578    @CheckForNull
3579    public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
3580      return unmodifiableOrNull(delegate.ceilingEntry(key));
3581    }
3582
3583    @Override
3584    @CheckForNull
3585    public K ceilingKey(@ParametricNullness K key) {
3586      return delegate.ceilingKey(key);
3587    }
3588
3589    @Override
3590    @CheckForNull
3591    public Entry<K, V> higherEntry(@ParametricNullness K key) {
3592      return unmodifiableOrNull(delegate.higherEntry(key));
3593    }
3594
3595    @Override
3596    @CheckForNull
3597    public K higherKey(@ParametricNullness K key) {
3598      return delegate.higherKey(key);
3599    }
3600
3601    @Override
3602    @CheckForNull
3603    public Entry<K, V> firstEntry() {
3604      return unmodifiableOrNull(delegate.firstEntry());
3605    }
3606
3607    @Override
3608    @CheckForNull
3609    public Entry<K, V> lastEntry() {
3610      return unmodifiableOrNull(delegate.lastEntry());
3611    }
3612
3613    @Override
3614    @CheckForNull
3615    public final Entry<K, V> pollFirstEntry() {
3616      throw new UnsupportedOperationException();
3617    }
3618
3619    @Override
3620    @CheckForNull
3621    public final Entry<K, V> pollLastEntry() {
3622      throw new UnsupportedOperationException();
3623    }
3624
3625    @Override
3626    public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
3627      throw new UnsupportedOperationException();
3628    }
3629
3630    @Override
3631    @CheckForNull
3632    public V putIfAbsent(K key, V value) {
3633      throw new UnsupportedOperationException();
3634    }
3635
3636    @Override
3637    public boolean remove(@Nullable Object key, @Nullable Object value) {
3638      throw new UnsupportedOperationException();
3639    }
3640
3641    @Override
3642    public boolean replace(K key, V oldValue, V newValue) {
3643      throw new UnsupportedOperationException();
3644    }
3645
3646    @Override
3647    @CheckForNull
3648    public V replace(K key, V value) {
3649      throw new UnsupportedOperationException();
3650    }
3651
3652    @Override
3653    public V computeIfAbsent(
3654        K key, java.util.function.Function<? super K, ? extends V> mappingFunction) {
3655      throw new UnsupportedOperationException();
3656    }
3657
3658    /*
3659     * TODO(cpovirk): Uncomment the @NonNull annotations below once our JDK stubs and J2KT
3660     * emulations include them.
3661     */
3662    @Override
3663    @CheckForNull
3664    public V computeIfPresent(
3665        K key,
3666        BiFunction<? super K, ? super /*@NonNull*/ V, ? extends @Nullable V> remappingFunction) {
3667      throw new UnsupportedOperationException();
3668    }
3669
3670    @Override
3671    @CheckForNull
3672    public V compute(
3673        K key,
3674        BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) {
3675      throw new UnsupportedOperationException();
3676    }
3677
3678    @Override
3679    @CheckForNull
3680    public V merge(
3681        K key,
3682        /*@NonNull*/ V value,
3683        BiFunction<? super /*@NonNull*/ V, ? super /*@NonNull*/ V, ? extends @Nullable V>
3684            function) {
3685      throw new UnsupportedOperationException();
3686    }
3687
3688    @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap;
3689
3690    @Override
3691    public NavigableMap<K, V> descendingMap() {
3692      UnmodifiableNavigableMap<K, V> result = descendingMap;
3693      return (result == null)
3694          ? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this)
3695          : result;
3696    }
3697
3698    @Override
3699    public Set<K> keySet() {
3700      return navigableKeySet();
3701    }
3702
3703    @Override
3704    public NavigableSet<K> navigableKeySet() {
3705      return Sets.unmodifiableNavigableSet(delegate.navigableKeySet());
3706    }
3707
3708    @Override
3709    public NavigableSet<K> descendingKeySet() {
3710      return Sets.unmodifiableNavigableSet(delegate.descendingKeySet());
3711    }
3712
3713    @Override
3714    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
3715      return subMap(fromKey, true, toKey, false);
3716    }
3717
3718    @Override
3719    public NavigableMap<K, V> subMap(
3720        @ParametricNullness K fromKey,
3721        boolean fromInclusive,
3722        @ParametricNullness K toKey,
3723        boolean toInclusive) {
3724      return Maps.unmodifiableNavigableMap(
3725          delegate.subMap(fromKey, fromInclusive, toKey, toInclusive));
3726    }
3727
3728    @Override
3729    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
3730      return headMap(toKey, false);
3731    }
3732
3733    @Override
3734    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
3735      return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive));
3736    }
3737
3738    @Override
3739    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
3740      return tailMap(fromKey, true);
3741    }
3742
3743    @Override
3744    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
3745      return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive));
3746    }
3747  }
3748
3749  /**
3750   * Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In
3751   * order to guarantee serial access, it is critical that <b>all</b> access to the backing
3752   * navigable map is accomplished through the returned navigable map (or its views).
3753   *
3754   * <p>It is imperative that the user manually synchronize on the returned navigable map when
3755   * iterating over any of its collection views, or the collections views of any of its {@code
3756   * descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views.
3757   *
3758   * <pre>{@code
3759   * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
3760   *
3761   * // Needn't be in synchronized block
3762   * NavigableSet<K> set = map.navigableKeySet();
3763   *
3764   * synchronized (map) { // Synchronizing on map, not set!
3765   *   Iterator<K> it = set.iterator(); // Must be in synchronized block
3766   *   while (it.hasNext()) {
3767   *     foo(it.next());
3768   *   }
3769   * }
3770   * }</pre>
3771   *
3772   * <p>or:
3773   *
3774   * <pre>{@code
3775   * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>());
3776   * NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true);
3777   *
3778   * // Needn't be in synchronized block
3779   * NavigableSet<K> set2 = map2.descendingKeySet();
3780   *
3781   * synchronized (map) { // Synchronizing on map, not map2 or set2!
3782   *   Iterator<K> it = set2.iterator(); // Must be in synchronized block
3783   *   while (it.hasNext()) {
3784   *     foo(it.next());
3785   *   }
3786   * }
3787   * }</pre>
3788   *
3789   * <p>Failure to follow this advice may result in non-deterministic behavior.
3790   *
3791   * <p>The returned navigable map will be serializable if the specified navigable map is
3792   * serializable.
3793   *
3794   * @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map.
3795   * @return a synchronized view of the specified navigable map.
3796   * @since 13.0
3797   */
3798  @GwtIncompatible // NavigableMap
3799  public static <K extends @Nullable Object, V extends @Nullable Object>
3800      NavigableMap<K, V> synchronizedNavigableMap(NavigableMap<K, V> navigableMap) {
3801    return Synchronized.navigableMap(navigableMap);
3802  }
3803
3804  /**
3805   * {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and
3806   * entrySet views.
3807   */
3808  @GwtCompatible
3809  abstract static class ViewCachingAbstractMap<
3810          K extends @Nullable Object, V extends @Nullable Object>
3811      extends AbstractMap<K, V> {
3812    /**
3813     * Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most
3814     * once on a given map, at the time when {@code entrySet} is first called.
3815     */
3816    abstract Set<Entry<K, V>> createEntrySet();
3817
3818    @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
3819
3820    @Override
3821    public Set<Entry<K, V>> entrySet() {
3822      Set<Entry<K, V>> result = entrySet;
3823      return (result == null) ? entrySet = createEntrySet() : result;
3824    }
3825
3826    @LazyInit @CheckForNull private transient Set<K> keySet;
3827
3828    @Override
3829    public Set<K> keySet() {
3830      Set<K> result = keySet;
3831      return (result == null) ? keySet = createKeySet() : result;
3832    }
3833
3834    Set<K> createKeySet() {
3835      return new KeySet<>(this);
3836    }
3837
3838    @LazyInit @CheckForNull private transient Collection<V> values;
3839
3840    @Override
3841    public Collection<V> values() {
3842      Collection<V> result = values;
3843      return (result == null) ? values = createValues() : result;
3844    }
3845
3846    Collection<V> createValues() {
3847      return new Values<>(this);
3848    }
3849  }
3850
3851  abstract static class IteratorBasedAbstractMap<
3852          K extends @Nullable Object, V extends @Nullable Object>
3853      extends AbstractMap<K, V> {
3854    @Override
3855    public abstract int size();
3856
3857    abstract Iterator<Entry<K, V>> entryIterator();
3858
3859    Spliterator<Entry<K, V>> entrySpliterator() {
3860      return Spliterators.spliterator(
3861          entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT);
3862    }
3863
3864    @Override
3865    public Set<Entry<K, V>> entrySet() {
3866      return new EntrySet<K, V>() {
3867        @Override
3868        Map<K, V> map() {
3869          return IteratorBasedAbstractMap.this;
3870        }
3871
3872        @Override
3873        public Iterator<Entry<K, V>> iterator() {
3874          return entryIterator();
3875        }
3876
3877        @Override
3878        public Spliterator<Entry<K, V>> spliterator() {
3879          return entrySpliterator();
3880        }
3881
3882        @Override
3883        public void forEach(Consumer<? super Entry<K, V>> action) {
3884          forEachEntry(action);
3885        }
3886      };
3887    }
3888
3889    void forEachEntry(Consumer<? super Entry<K, V>> action) {
3890      entryIterator().forEachRemaining(action);
3891    }
3892
3893    @Override
3894    public void clear() {
3895      Iterators.clear(entryIterator());
3896    }
3897  }
3898
3899  /**
3900   * Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code
3901   * NullPointerException}.
3902   */
3903  @CheckForNull
3904  static <V extends @Nullable Object> V safeGet(Map<?, V> map, @CheckForNull Object key) {
3905    checkNotNull(map);
3906    try {
3907      return map.get(key);
3908    } catch (ClassCastException | NullPointerException e) {
3909      return null;
3910    }
3911  }
3912
3913  /**
3914   * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and
3915   * {@code NullPointerException}.
3916   */
3917  static boolean safeContainsKey(Map<?, ?> map, @CheckForNull Object key) {
3918    checkNotNull(map);
3919    try {
3920      return map.containsKey(key);
3921    } catch (ClassCastException | NullPointerException e) {
3922      return false;
3923    }
3924  }
3925
3926  /**
3927   * Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code
3928   * NullPointerException}.
3929   */
3930  @CheckForNull
3931  static <V extends @Nullable Object> V safeRemove(Map<?, V> map, @CheckForNull Object key) {
3932    checkNotNull(map);
3933    try {
3934      return map.remove(key);
3935    } catch (ClassCastException | NullPointerException e) {
3936      return null;
3937    }
3938  }
3939
3940  /** An admittedly inefficient implementation of {@link Map#containsKey}. */
3941  static boolean containsKeyImpl(Map<?, ?> map, @CheckForNull Object key) {
3942    return Iterators.contains(keyIterator(map.entrySet().iterator()), key);
3943  }
3944
3945  /** An implementation of {@link Map#containsValue}. */
3946  static boolean containsValueImpl(Map<?, ?> map, @CheckForNull Object value) {
3947    return Iterators.contains(valueIterator(map.entrySet().iterator()), value);
3948  }
3949
3950  /**
3951   * Implements {@code Collection.contains} safely for forwarding collections of map entries. If
3952   * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
3953   * protect against a possible nefarious equals method.
3954   *
3955   * <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding
3956   * collection.
3957   *
3958   * @param c the delegate (unwrapped) collection of map entries
3959   * @param o the object that might be contained in {@code c}
3960   * @return {@code true} if {@code c} contains {@code o}
3961   */
3962  static <K extends @Nullable Object, V extends @Nullable Object> boolean containsEntryImpl(
3963      Collection<Entry<K, V>> c, @CheckForNull Object o) {
3964    if (!(o instanceof Entry)) {
3965      return false;
3966    }
3967    return c.contains(unmodifiableEntry((Entry<?, ?>) o));
3968  }
3969
3970  /**
3971   * Implements {@code Collection.remove} safely for forwarding collections of map entries. If
3972   * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to
3973   * protect against a possible nefarious equals method.
3974   *
3975   * <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection.
3976   *
3977   * @param c the delegate (unwrapped) collection of map entries
3978   * @param o the object to remove from {@code c}
3979   * @return {@code true} if {@code c} was changed
3980   */
3981  static <K extends @Nullable Object, V extends @Nullable Object> boolean removeEntryImpl(
3982      Collection<Entry<K, V>> c, @CheckForNull Object o) {
3983    if (!(o instanceof Entry)) {
3984      return false;
3985    }
3986    return c.remove(unmodifiableEntry((Entry<?, ?>) o));
3987  }
3988
3989  /** An implementation of {@link Map#equals}. */
3990  static boolean equalsImpl(Map<?, ?> map, @CheckForNull Object object) {
3991    if (map == object) {
3992      return true;
3993    } else if (object instanceof Map) {
3994      Map<?, ?> o = (Map<?, ?>) object;
3995      return map.entrySet().equals(o.entrySet());
3996    }
3997    return false;
3998  }
3999
4000  /** An implementation of {@link Map#toString}. */
4001  static String toStringImpl(Map<?, ?> map) {
4002    StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{');
4003    boolean first = true;
4004    for (Entry<?, ?> entry : map.entrySet()) {
4005      if (!first) {
4006        sb.append(", ");
4007      }
4008      first = false;
4009      sb.append(entry.getKey()).append('=').append(entry.getValue());
4010    }
4011    return sb.append('}').toString();
4012  }
4013
4014  /** An implementation of {@link Map#putAll}. */
4015  static <K extends @Nullable Object, V extends @Nullable Object> void putAllImpl(
4016      Map<K, V> self, Map<? extends K, ? extends V> map) {
4017    for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
4018      self.put(entry.getKey(), entry.getValue());
4019    }
4020  }
4021
4022  static class KeySet<K extends @Nullable Object, V extends @Nullable Object>
4023      extends Sets.ImprovedAbstractSet<K> {
4024    @Weak final Map<K, V> map;
4025
4026    KeySet(Map<K, V> map) {
4027      this.map = checkNotNull(map);
4028    }
4029
4030    Map<K, V> map() {
4031      return map;
4032    }
4033
4034    @Override
4035    public Iterator<K> iterator() {
4036      return keyIterator(map().entrySet().iterator());
4037    }
4038
4039    @Override
4040    public void forEach(Consumer<? super K> action) {
4041      checkNotNull(action);
4042      // avoids entry allocation for those maps that allocate entries on iteration
4043      map.forEach((k, v) -> action.accept(k));
4044    }
4045
4046    @Override
4047    public int size() {
4048      return map().size();
4049    }
4050
4051    @Override
4052    public boolean isEmpty() {
4053      return map().isEmpty();
4054    }
4055
4056    @Override
4057    public boolean contains(@CheckForNull Object o) {
4058      return map().containsKey(o);
4059    }
4060
4061    @Override
4062    public boolean remove(@CheckForNull Object o) {
4063      if (contains(o)) {
4064        map().remove(o);
4065        return true;
4066      }
4067      return false;
4068    }
4069
4070    @Override
4071    public void clear() {
4072      map().clear();
4073    }
4074  }
4075
4076  @CheckForNull
4077  static <K extends @Nullable Object> K keyOrNull(@CheckForNull Entry<K, ?> entry) {
4078    return (entry == null) ? null : entry.getKey();
4079  }
4080
4081  @CheckForNull
4082  static <V extends @Nullable Object> V valueOrNull(@CheckForNull Entry<?, V> entry) {
4083    return (entry == null) ? null : entry.getValue();
4084  }
4085
4086  static class SortedKeySet<K extends @Nullable Object, V extends @Nullable Object>
4087      extends KeySet<K, V> implements SortedSet<K> {
4088    SortedKeySet(SortedMap<K, V> map) {
4089      super(map);
4090    }
4091
4092    @Override
4093    SortedMap<K, V> map() {
4094      return (SortedMap<K, V>) super.map();
4095    }
4096
4097    @Override
4098    @CheckForNull
4099    public Comparator<? super K> comparator() {
4100      return map().comparator();
4101    }
4102
4103    @Override
4104    public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
4105      return new SortedKeySet<>(map().subMap(fromElement, toElement));
4106    }
4107
4108    @Override
4109    public SortedSet<K> headSet(@ParametricNullness K toElement) {
4110      return new SortedKeySet<>(map().headMap(toElement));
4111    }
4112
4113    @Override
4114    public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
4115      return new SortedKeySet<>(map().tailMap(fromElement));
4116    }
4117
4118    @Override
4119    @ParametricNullness
4120    public K first() {
4121      return map().firstKey();
4122    }
4123
4124    @Override
4125    @ParametricNullness
4126    public K last() {
4127      return map().lastKey();
4128    }
4129  }
4130
4131  @GwtIncompatible // NavigableMap
4132  static class NavigableKeySet<K extends @Nullable Object, V extends @Nullable Object>
4133      extends SortedKeySet<K, V> implements NavigableSet<K> {
4134    NavigableKeySet(NavigableMap<K, V> map) {
4135      super(map);
4136    }
4137
4138    @Override
4139    NavigableMap<K, V> map() {
4140      return (NavigableMap<K, V>) map;
4141    }
4142
4143    @Override
4144    @CheckForNull
4145    public K lower(@ParametricNullness K e) {
4146      return map().lowerKey(e);
4147    }
4148
4149    @Override
4150    @CheckForNull
4151    public K floor(@ParametricNullness K e) {
4152      return map().floorKey(e);
4153    }
4154
4155    @Override
4156    @CheckForNull
4157    public K ceiling(@ParametricNullness K e) {
4158      return map().ceilingKey(e);
4159    }
4160
4161    @Override
4162    @CheckForNull
4163    public K higher(@ParametricNullness K e) {
4164      return map().higherKey(e);
4165    }
4166
4167    @Override
4168    @CheckForNull
4169    public K pollFirst() {
4170      return keyOrNull(map().pollFirstEntry());
4171    }
4172
4173    @Override
4174    @CheckForNull
4175    public K pollLast() {
4176      return keyOrNull(map().pollLastEntry());
4177    }
4178
4179    @Override
4180    public NavigableSet<K> descendingSet() {
4181      return map().descendingKeySet();
4182    }
4183
4184    @Override
4185    public Iterator<K> descendingIterator() {
4186      return descendingSet().iterator();
4187    }
4188
4189    @Override
4190    public NavigableSet<K> subSet(
4191        @ParametricNullness K fromElement,
4192        boolean fromInclusive,
4193        @ParametricNullness K toElement,
4194        boolean toInclusive) {
4195      return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet();
4196    }
4197
4198    @Override
4199    public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) {
4200      return subSet(fromElement, true, toElement, false);
4201    }
4202
4203    @Override
4204    public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) {
4205      return map().headMap(toElement, inclusive).navigableKeySet();
4206    }
4207
4208    @Override
4209    public SortedSet<K> headSet(@ParametricNullness K toElement) {
4210      return headSet(toElement, false);
4211    }
4212
4213    @Override
4214    public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) {
4215      return map().tailMap(fromElement, inclusive).navigableKeySet();
4216    }
4217
4218    @Override
4219    public SortedSet<K> tailSet(@ParametricNullness K fromElement) {
4220      return tailSet(fromElement, true);
4221    }
4222  }
4223
4224  static class Values<K extends @Nullable Object, V extends @Nullable Object>
4225      extends AbstractCollection<V> {
4226    @Weak final Map<K, V> map;
4227
4228    Values(Map<K, V> map) {
4229      this.map = checkNotNull(map);
4230    }
4231
4232    final Map<K, V> map() {
4233      return map;
4234    }
4235
4236    @Override
4237    public Iterator<V> iterator() {
4238      return valueIterator(map().entrySet().iterator());
4239    }
4240
4241    @Override
4242    public void forEach(Consumer<? super V> action) {
4243      checkNotNull(action);
4244      // avoids allocation of entries for those maps that generate fresh entries on iteration
4245      map.forEach((k, v) -> action.accept(v));
4246    }
4247
4248    @Override
4249    public boolean remove(@CheckForNull Object o) {
4250      try {
4251        return super.remove(o);
4252      } catch (UnsupportedOperationException e) {
4253        for (Entry<K, V> entry : map().entrySet()) {
4254          if (Objects.equal(o, entry.getValue())) {
4255            map().remove(entry.getKey());
4256            return true;
4257          }
4258        }
4259        return false;
4260      }
4261    }
4262
4263    @Override
4264    public boolean removeAll(Collection<?> c) {
4265      try {
4266        return super.removeAll(checkNotNull(c));
4267      } catch (UnsupportedOperationException e) {
4268        Set<K> toRemove = Sets.newHashSet();
4269        for (Entry<K, V> entry : map().entrySet()) {
4270          if (c.contains(entry.getValue())) {
4271            toRemove.add(entry.getKey());
4272          }
4273        }
4274        return map().keySet().removeAll(toRemove);
4275      }
4276    }
4277
4278    @Override
4279    public boolean retainAll(Collection<?> c) {
4280      try {
4281        return super.retainAll(checkNotNull(c));
4282      } catch (UnsupportedOperationException e) {
4283        Set<K> toRetain = Sets.newHashSet();
4284        for (Entry<K, V> entry : map().entrySet()) {
4285          if (c.contains(entry.getValue())) {
4286            toRetain.add(entry.getKey());
4287          }
4288        }
4289        return map().keySet().retainAll(toRetain);
4290      }
4291    }
4292
4293    @Override
4294    public int size() {
4295      return map().size();
4296    }
4297
4298    @Override
4299    public boolean isEmpty() {
4300      return map().isEmpty();
4301    }
4302
4303    @Override
4304    public boolean contains(@CheckForNull Object o) {
4305      return map().containsValue(o);
4306    }
4307
4308    @Override
4309    public void clear() {
4310      map().clear();
4311    }
4312  }
4313
4314  abstract static class EntrySet<K extends @Nullable Object, V extends @Nullable Object>
4315      extends Sets.ImprovedAbstractSet<Entry<K, V>> {
4316    abstract Map<K, V> map();
4317
4318    @Override
4319    public int size() {
4320      return map().size();
4321    }
4322
4323    @Override
4324    public void clear() {
4325      map().clear();
4326    }
4327
4328    @Override
4329    public boolean contains(@CheckForNull Object o) {
4330      if (o instanceof Entry) {
4331        Entry<?, ?> entry = (Entry<?, ?>) o;
4332        Object key = entry.getKey();
4333        V value = Maps.safeGet(map(), key);
4334        return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key));
4335      }
4336      return false;
4337    }
4338
4339    @Override
4340    public boolean isEmpty() {
4341      return map().isEmpty();
4342    }
4343
4344    @Override
4345    public boolean remove(@CheckForNull Object o) {
4346      /*
4347       * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
4348       * nullness checker.
4349       */
4350      if (contains(o) && o instanceof Entry) {
4351        Entry<?, ?> entry = (Entry<?, ?>) o;
4352        return map().keySet().remove(entry.getKey());
4353      }
4354      return false;
4355    }
4356
4357    @Override
4358    public boolean removeAll(Collection<?> c) {
4359      try {
4360        return super.removeAll(checkNotNull(c));
4361      } catch (UnsupportedOperationException e) {
4362        // if the iterators don't support remove
4363        return Sets.removeAllImpl(this, c.iterator());
4364      }
4365    }
4366
4367    @Override
4368    public boolean retainAll(Collection<?> c) {
4369      try {
4370        return super.retainAll(checkNotNull(c));
4371      } catch (UnsupportedOperationException e) {
4372        // if the iterators don't support remove
4373        Set<@Nullable Object> keys = Sets.newHashSetWithExpectedSize(c.size());
4374        for (Object o : c) {
4375          /*
4376           * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our
4377           * nullness checker.
4378           */
4379          if (contains(o) && o instanceof Entry) {
4380            Entry<?, ?> entry = (Entry<?, ?>) o;
4381            keys.add(entry.getKey());
4382          }
4383        }
4384        return map().keySet().retainAll(keys);
4385      }
4386    }
4387  }
4388
4389  @GwtIncompatible // NavigableMap
4390  abstract static class DescendingMap<K extends @Nullable Object, V extends @Nullable Object>
4391      extends ForwardingMap<K, V> implements NavigableMap<K, V> {
4392
4393    abstract NavigableMap<K, V> forward();
4394
4395    @Override
4396    protected final Map<K, V> delegate() {
4397      return forward();
4398    }
4399
4400    @LazyInit @CheckForNull private transient Comparator<? super K> comparator;
4401
4402    @SuppressWarnings("unchecked")
4403    @Override
4404    public Comparator<? super K> comparator() {
4405      Comparator<? super K> result = comparator;
4406      if (result == null) {
4407        Comparator<? super K> forwardCmp = forward().comparator();
4408        if (forwardCmp == null) {
4409          forwardCmp = (Comparator) Ordering.natural();
4410        }
4411        result = comparator = reverse(forwardCmp);
4412      }
4413      return result;
4414    }
4415
4416    // If we inline this, we get a javac error.
4417    private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) {
4418      return Ordering.from(forward).reverse();
4419    }
4420
4421    @Override
4422    @ParametricNullness
4423    public K firstKey() {
4424      return forward().lastKey();
4425    }
4426
4427    @Override
4428    @ParametricNullness
4429    public K lastKey() {
4430      return forward().firstKey();
4431    }
4432
4433    @Override
4434    @CheckForNull
4435    public Entry<K, V> lowerEntry(@ParametricNullness K key) {
4436      return forward().higherEntry(key);
4437    }
4438
4439    @Override
4440    @CheckForNull
4441    public K lowerKey(@ParametricNullness K key) {
4442      return forward().higherKey(key);
4443    }
4444
4445    @Override
4446    @CheckForNull
4447    public Entry<K, V> floorEntry(@ParametricNullness K key) {
4448      return forward().ceilingEntry(key);
4449    }
4450
4451    @Override
4452    @CheckForNull
4453    public K floorKey(@ParametricNullness K key) {
4454      return forward().ceilingKey(key);
4455    }
4456
4457    @Override
4458    @CheckForNull
4459    public Entry<K, V> ceilingEntry(@ParametricNullness K key) {
4460      return forward().floorEntry(key);
4461    }
4462
4463    @Override
4464    @CheckForNull
4465    public K ceilingKey(@ParametricNullness K key) {
4466      return forward().floorKey(key);
4467    }
4468
4469    @Override
4470    @CheckForNull
4471    public Entry<K, V> higherEntry(@ParametricNullness K key) {
4472      return forward().lowerEntry(key);
4473    }
4474
4475    @Override
4476    @CheckForNull
4477    public K higherKey(@ParametricNullness K key) {
4478      return forward().lowerKey(key);
4479    }
4480
4481    @Override
4482    @CheckForNull
4483    public Entry<K, V> firstEntry() {
4484      return forward().lastEntry();
4485    }
4486
4487    @Override
4488    @CheckForNull
4489    public Entry<K, V> lastEntry() {
4490      return forward().firstEntry();
4491    }
4492
4493    @Override
4494    @CheckForNull
4495    public Entry<K, V> pollFirstEntry() {
4496      return forward().pollLastEntry();
4497    }
4498
4499    @Override
4500    @CheckForNull
4501    public Entry<K, V> pollLastEntry() {
4502      return forward().pollFirstEntry();
4503    }
4504
4505    @Override
4506    public NavigableMap<K, V> descendingMap() {
4507      return forward();
4508    }
4509
4510    @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet;
4511
4512    @Override
4513    public Set<Entry<K, V>> entrySet() {
4514      Set<Entry<K, V>> result = entrySet;
4515      return (result == null) ? entrySet = createEntrySet() : result;
4516    }
4517
4518    abstract Iterator<Entry<K, V>> entryIterator();
4519
4520    Set<Entry<K, V>> createEntrySet() {
4521      @WeakOuter
4522      class EntrySetImpl extends EntrySet<K, V> {
4523        @Override
4524        Map<K, V> map() {
4525          return DescendingMap.this;
4526        }
4527
4528        @Override
4529        public Iterator<Entry<K, V>> iterator() {
4530          return entryIterator();
4531        }
4532      }
4533      return new EntrySetImpl();
4534    }
4535
4536    @Override
4537    public Set<K> keySet() {
4538      return navigableKeySet();
4539    }
4540
4541    @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet;
4542
4543    @Override
4544    public NavigableSet<K> navigableKeySet() {
4545      NavigableSet<K> result = navigableKeySet;
4546      return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result;
4547    }
4548
4549    @Override
4550    public NavigableSet<K> descendingKeySet() {
4551      return forward().navigableKeySet();
4552    }
4553
4554    @Override
4555    public NavigableMap<K, V> subMap(
4556        @ParametricNullness K fromKey,
4557        boolean fromInclusive,
4558        @ParametricNullness K toKey,
4559        boolean toInclusive) {
4560      return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap();
4561    }
4562
4563    @Override
4564    public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) {
4565      return subMap(fromKey, true, toKey, false);
4566    }
4567
4568    @Override
4569    public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) {
4570      return forward().tailMap(toKey, inclusive).descendingMap();
4571    }
4572
4573    @Override
4574    public SortedMap<K, V> headMap(@ParametricNullness K toKey) {
4575      return headMap(toKey, false);
4576    }
4577
4578    @Override
4579    public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) {
4580      return forward().headMap(fromKey, inclusive).descendingMap();
4581    }
4582
4583    @Override
4584    public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) {
4585      return tailMap(fromKey, true);
4586    }
4587
4588    @Override
4589    public Collection<V> values() {
4590      return new Values<>(this);
4591    }
4592
4593    @Override
4594    public String toString() {
4595      return standardToString();
4596    }
4597  }
4598
4599  /** Returns a map from the ith element of list to i. */
4600  static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) {
4601    ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size());
4602    int i = 0;
4603    for (E e : list) {
4604      builder.put(e, i++);
4605    }
4606    return builder.buildOrThrow();
4607  }
4608
4609  /**
4610   * Returns a view of the portion of {@code map} whose keys are contained by {@code range}.
4611   *
4612   * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link
4613   * NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link
4614   * NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object,
4615   * boolean) headMap()}) to actually construct the view. Consult these methods for a full
4616   * description of the returned view's behavior.
4617   *
4618   * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural
4619   * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link
4620   * Comparator}, which can violate the natural ordering. Using this method (or in general using
4621   * {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior.
4622   *
4623   * @since 20.0
4624   */
4625  @GwtIncompatible // NavigableMap
4626  public static <K extends Comparable<? super K>, V extends @Nullable Object>
4627      NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) {
4628    if (map.comparator() != null
4629        && map.comparator() != Ordering.natural()
4630        && range.hasLowerBound()
4631        && range.hasUpperBound()) {
4632      checkArgument(
4633          map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0,
4634          "map is using a custom comparator which is inconsistent with the natural ordering.");
4635    }
4636    if (range.hasLowerBound() && range.hasUpperBound()) {
4637      return map.subMap(
4638          range.lowerEndpoint(),
4639          range.lowerBoundType() == BoundType.CLOSED,
4640          range.upperEndpoint(),
4641          range.upperBoundType() == BoundType.CLOSED);
4642    } else if (range.hasLowerBound()) {
4643      return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED);
4644    } else if (range.hasUpperBound()) {
4645      return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED);
4646    }
4647    return checkNotNull(map);
4648  }
4649}