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