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