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