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