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