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