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