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