All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.google.common.collect.Maps Maven / Gradle / Ivy

There is a newer version: 3.9
Show newest version
/*
 * Copyright (C) 2007 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.MapDifference.ValueDifference;
import com.google.common.primitives.Ints;

import java.io.Serializable;
import java.util.AbstractCollection;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentMap;

import javax.annotation.Nullable;

/**
 * Static utility methods pertaining to {@link Map} instances (including instances of
 * {@link SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts
 * {@link Lists}, {@link Sets} and {@link Queues}.
 *
 * 

See the Guava User Guide article on * {@code Maps}. * * @author Kevin Bourrillion * @author Mike Bostock * @author Isaac Shum * @author Louis Wasserman * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Maps { private Maps() {} private enum EntryFunction implements Function { KEY { @Override @Nullable public Object apply(Entry entry) { return entry.getKey(); } }, VALUE { @Override @Nullable public Object apply(Entry entry) { return entry.getValue(); } }; } @SuppressWarnings("unchecked") static Function, K> keyFunction() { return (Function) EntryFunction.KEY; } static Function, V> valueFunction() { return (Function) EntryFunction.VALUE; } /** * Returns an immutable map instance containing the given entries. * Internally, the returned set will be backed by an {@link EnumMap}. * *

The iteration order of the returned map follows the enum's iteration * order, not the order in which the elements appear in the given map. * * @param map the map to make an immutable copy of * @return an immutable map containing those entries * @since 14.0 */ @GwtCompatible(serializable = true) @Beta public static , V> ImmutableMap immutableEnumMap( Map map) { if (map instanceof ImmutableEnumMap) { return (ImmutableEnumMap) map; } else if (map.isEmpty()) { return ImmutableMap.of(); } else { for (Map.Entry entry : map.entrySet()) { checkNotNull(entry.getKey()); checkNotNull(entry.getValue()); } return ImmutableEnumMap.asImmutable(new EnumMap(map)); } } /** * Creates a mutable, empty {@code HashMap} instance. * *

Note: if mutability is not required, use {@link * ImmutableMap#of()} instead. * *

Note: if {@code K} is an {@code enum} type, use {@link * #newEnumMap} instead. * * @return a new, empty {@code HashMap} */ public static HashMap newHashMap() { return new HashMap(); } /** * Creates a {@code HashMap} instance, with a high enough "initial capacity" * that it should hold {@code expectedSize} elements without growth. * This behavior cannot be broadly guaranteed, but it is observed to be true * for OpenJDK 1.6. It also can't be guaranteed that the method isn't * inadvertently oversizing the returned map. * * @param expectedSize the number of elements you expect to add to the * returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code * expectedSize} elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static HashMap newHashMapWithExpectedSize( int expectedSize) { return new HashMap(capacity(expectedSize)); } /** * Returns a capacity that is sufficient to keep the map from being resized as * long as it grows no larger than expectedSize and the load factor is >= its * default (0.75). */ static int capacity(int expectedSize) { if (expectedSize < 3) { checkArgument(expectedSize >= 0); return expectedSize + 1; } if (expectedSize < Ints.MAX_POWER_OF_TWO) { return expectedSize + expectedSize / 3; } return Integer.MAX_VALUE; // any large value } /** * Creates a mutable {@code HashMap} instance with the same mappings as * the specified map. * *

Note: if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * *

Note: if {@code K} is an {@link Enum} type, use {@link * #newEnumMap} instead. * * @param map the mappings to be placed in the new map * @return a new {@code HashMap} initialized with the mappings from {@code * map} */ public static HashMap newHashMap( Map map) { return new HashMap(map); } /** * Creates a mutable, empty, insertion-ordered {@code LinkedHashMap} * instance. * *

Note: if mutability is not required, use {@link * ImmutableMap#of()} instead. * * @return a new, empty {@code LinkedHashMap} */ public static LinkedHashMap newLinkedHashMap() { return new LinkedHashMap(); } /** * Creates a mutable, insertion-ordered {@code LinkedHashMap} instance * with the same mappings as the specified map. * *

Note: if mutability is not required, use {@link * ImmutableMap#copyOf(Map)} instead. * * @param map the mappings to be placed in the new map * @return a new, {@code LinkedHashMap} initialized with the mappings from * {@code map} */ public static LinkedHashMap newLinkedHashMap( Map map) { return new LinkedHashMap(map); } /** * Returns a general-purpose instance of {@code ConcurrentMap}, which supports * all optional operations of the ConcurrentMap interface. It does not permit * null keys or values. It is serializable. * *

This is currently accomplished by calling {@link MapMaker#makeMap()}. * *

It is preferable to use {@code MapMaker} directly (rather than through * this method), as it presents numerous useful configuration options, * such as the concurrency level, load factor, key/value reference types, * and value computation. * * @return a new, empty {@code ConcurrentMap} * @since 3.0 */ public static ConcurrentMap newConcurrentMap() { return new MapMaker().makeMap(); } /** * Creates a mutable, empty {@code TreeMap} instance using the natural * ordering of its elements. * *

Note: if mutability is not required, use {@link * ImmutableSortedMap#of()} instead. * * @return a new, empty {@code TreeMap} */ public static TreeMap newTreeMap() { return new TreeMap(); } /** * Creates a mutable {@code TreeMap} instance with the same mappings as * the specified map and using the same ordering as the specified map. * *

Note: if mutability is not required, use {@link * ImmutableSortedMap#copyOfSorted(SortedMap)} instead. * * @param map the sorted map whose mappings are to be placed in the new map * and whose comparator is to be used to sort the new map * @return a new {@code TreeMap} initialized with the mappings from {@code * map} and using the comparator of {@code map} */ public static TreeMap newTreeMap(SortedMap map) { return new TreeMap(map); } /** * Creates a mutable, empty {@code TreeMap} instance using the given * comparator. * *

Note: if mutability is not required, use {@code * ImmutableSortedMap.orderedBy(comparator).build()} instead. * * @param comparator the comparator to sort the keys with * @return a new, empty {@code TreeMap} */ public static TreeMap newTreeMap( @Nullable Comparator comparator) { // Ideally, the extra type parameter "C" shouldn't be necessary. It is a // work-around of a compiler type inference quirk that prevents the // following code from being compiled: // Comparator> comparator = null; // Map, String> map = newTreeMap(comparator); return new TreeMap(comparator); } /** * Creates an {@code EnumMap} instance. * * @param type the key type for this map * @return a new, empty {@code EnumMap} */ public static , V> EnumMap newEnumMap(Class type) { return new EnumMap(checkNotNull(type)); } /** * Creates an {@code EnumMap} with the same mappings as the specified map. * * @param map the map from which to initialize this {@code EnumMap} * @return a new {@code EnumMap} initialized with the mappings from {@code * map} * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} * instance and contains no mappings */ public static , V> EnumMap newEnumMap( Map map) { return new EnumMap(map); } /** * Creates an {@code IdentityHashMap} instance. * * @return a new, empty {@code IdentityHashMap} */ public static IdentityHashMap newIdentityHashMap() { return new IdentityHashMap(); } /** * Computes the difference between two maps. This difference is an immutable * snapshot of the state of the maps at the time this method is called. It * will never change, even if the maps change at a later time. * *

Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * *

Note:If you only need to know whether two maps have the same * mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps */ @SuppressWarnings("unchecked") public static MapDifference difference( Map left, Map right) { if (left instanceof SortedMap) { SortedMap sortedLeft = (SortedMap) left; SortedMapDifference result = difference(sortedLeft, right); return result; } return difference(left, right, Equivalence.equals()); } /** * Computes the difference between two maps. This difference is an immutable * snapshot of the state of the maps at the time this method is called. It * will never change, even if the maps change at a later time. * *

Values are compared using a provided equivalence, in the case of * equality, the value on the 'left' is returned in the difference. * *

Since this method uses {@code HashMap} instances internally, the keys of * the supplied maps must be well-behaved with respect to * {@link Object#equals} and {@link Object#hashCode}. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @param valueEquivalence the equivalence relationship to use to compare * values * @return the difference between the two maps * @since 10.0 */ @Beta public static MapDifference difference( Map left, Map right, Equivalence valueEquivalence) { Preconditions.checkNotNull(valueEquivalence); Map onlyOnLeft = newHashMap(); Map onlyOnRight = new HashMap(right); // will whittle it down Map onBoth = newHashMap(); Map> differences = newHashMap(); boolean eq = true; for (Entry entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { V rightValue = onlyOnRight.remove(leftKey); if (valueEquivalence.equivalent(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { eq = false; differences.put( leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { eq = false; onlyOnLeft.put(leftKey, leftValue); } } boolean areEqual = eq && onlyOnRight.isEmpty(); return mapDifference( areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } private static MapDifference mapDifference(boolean areEqual, Map onlyOnLeft, Map onlyOnRight, Map onBoth, Map> differences) { return new MapDifferenceImpl(areEqual, Collections.unmodifiableMap(onlyOnLeft), Collections.unmodifiableMap(onlyOnRight), Collections.unmodifiableMap(onBoth), Collections.unmodifiableMap(differences)); } static class MapDifferenceImpl implements MapDifference { final boolean areEqual; final Map onlyOnLeft; final Map onlyOnRight; final Map onBoth; final Map> differences; MapDifferenceImpl(boolean areEqual, Map onlyOnLeft, Map onlyOnRight, Map onBoth, Map> differences) { this.areEqual = areEqual; this.onlyOnLeft = onlyOnLeft; this.onlyOnRight = onlyOnRight; this.onBoth = onBoth; this.differences = differences; } @Override public boolean areEqual() { return areEqual; } @Override public Map entriesOnlyOnLeft() { return onlyOnLeft; } @Override public Map entriesOnlyOnRight() { return onlyOnRight; } @Override public Map entriesInCommon() { return onBoth; } @Override public Map> entriesDiffering() { return differences; } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof MapDifference) { MapDifference other = (MapDifference) object; return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft()) && entriesOnlyOnRight().equals(other.entriesOnlyOnRight()) && entriesInCommon().equals(other.entriesInCommon()) && entriesDiffering().equals(other.entriesDiffering()); } return false; } @Override public int hashCode() { return Objects.hashCode(entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering()); } @Override public String toString() { if (areEqual) { return "equal"; } StringBuilder result = new StringBuilder("not equal"); if (!onlyOnLeft.isEmpty()) { result.append(": only on left=").append(onlyOnLeft); } if (!onlyOnRight.isEmpty()) { result.append(": only on right=").append(onlyOnRight); } if (!differences.isEmpty()) { result.append(": value differences=").append(differences); } return result.toString(); } } static class ValueDifferenceImpl implements MapDifference.ValueDifference { private final V left; private final V right; static ValueDifference create(@Nullable V left, @Nullable V right) { return new ValueDifferenceImpl(left, right); } private ValueDifferenceImpl(@Nullable V left, @Nullable V right) { this.left = left; this.right = right; } @Override public V leftValue() { return left; } @Override public V rightValue() { return right; } @Override public boolean equals(@Nullable Object object) { if (object instanceof MapDifference.ValueDifference) { MapDifference.ValueDifference that = (MapDifference.ValueDifference) object; return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(left, right); } @Override public String toString() { return "(" + left + ", " + right + ")"; } } /** * Computes the difference between two sorted maps, using the comparator of * the left map, or {@code Ordering.natural()} if the left map uses the * natural ordering of its elements. This difference is an immutable snapshot * of the state of the maps at the time this method is called. It will never * change, even if the maps change at a later time. * *

Since this method uses {@code TreeMap} instances internally, the keys of * the right map must all compare as distinct according to the comparator * of the left map. * *

Note:If you only need to know whether two sorted maps have the * same mappings, call {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps * @since 11.0 */ public static SortedMapDifference difference( SortedMap left, Map right) { checkNotNull(left); checkNotNull(right); Comparator comparator = orNaturalOrder(left.comparator()); SortedMap onlyOnLeft = Maps.newTreeMap(comparator); SortedMap onlyOnRight = Maps.newTreeMap(comparator); onlyOnRight.putAll(right); // will whittle it down SortedMap onBoth = Maps.newTreeMap(comparator); SortedMap> differences = Maps.newTreeMap(comparator); boolean eq = true; for (Entry entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { V rightValue = onlyOnRight.remove(leftKey); if (Objects.equal(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { eq = false; differences.put( leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { eq = false; onlyOnLeft.put(leftKey, leftValue); } } boolean areEqual = eq && onlyOnRight.isEmpty(); return sortedMapDifference( areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } private static SortedMapDifference sortedMapDifference( boolean areEqual, SortedMap onlyOnLeft, SortedMap onlyOnRight, SortedMap onBoth, SortedMap> differences) { return new SortedMapDifferenceImpl(areEqual, Collections.unmodifiableSortedMap(onlyOnLeft), Collections.unmodifiableSortedMap(onlyOnRight), Collections.unmodifiableSortedMap(onBoth), Collections.unmodifiableSortedMap(differences)); } static class SortedMapDifferenceImpl extends MapDifferenceImpl implements SortedMapDifference { SortedMapDifferenceImpl(boolean areEqual, SortedMap onlyOnLeft, SortedMap onlyOnRight, SortedMap onBoth, SortedMap> differences) { super(areEqual, onlyOnLeft, onlyOnRight, onBoth, differences); } @Override public SortedMap> entriesDiffering() { return (SortedMap>) super.entriesDiffering(); } @Override public SortedMap entriesInCommon() { return (SortedMap) super.entriesInCommon(); } @Override public SortedMap entriesOnlyOnLeft() { return (SortedMap) super.entriesOnlyOnLeft(); } @Override public SortedMap entriesOnlyOnRight() { return (SortedMap) super.entriesOnlyOnRight(); } } /** * Returns the specified comparator if not null; otherwise returns {@code * Ordering.natural()}. This method is an abomination of generics; the only * purpose of this method is to contain the ugly type-casting in one place. */ @SuppressWarnings("unchecked") static Comparator orNaturalOrder( @Nullable Comparator comparator) { if (comparator != null) { // can't use ? : because of javac bug 5080917 return comparator; } return (Comparator) Ordering.natural(); } /** * Returns a view of the set as a map, mapping keys from the set according to * the specified function. * *

Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * *

Modifications to the backing set are read through to the returned map. * The returned map supports removal operations if the backing set does. * Removal operations write through to the backing set. The returned map * does not support put operations. * *

Warning: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * *

Warning: This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also * of type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta public static Map asMap( Set set, Function function) { if (set instanceof SortedSet) { return asMap((SortedSet) set, function); } else { return new AsMapView(set, function); } } /** * Returns a view of the sorted set as a map, mapping keys from the set * according to the specified function. * *

Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * *

Modifications to the backing set are read through to the returned map. * The returned map supports removal operations if the backing set does. * Removal operations write through to the backing set. The returned map does * not support put operations. * *

Warning: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * *

Warning: This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta public static SortedMap asMap( SortedSet set, Function function) { return Platform.mapsAsMapSortedSet(set, function); } static SortedMap asMapSortedIgnoreNavigable(SortedSet set, Function function) { return new SortedAsMapView(set, function); } /** * Returns a view of the navigable set as a map, mapping keys from the set * according to the specified function. * *

Specifically, for each {@code k} in the backing set, the returned map * has an entry mapping {@code k} to {@code function.apply(k)}. The {@code * keySet}, {@code values}, and {@code entrySet} views of the returned map * iterate in the same order as the backing set. * *

Modifications to the backing set are read through to the returned map. * The returned map supports removal operations if the backing set does. * Removal operations write through to the backing set. The returned map * does not support put operations. * *

Warning: If the function rejects {@code null}, caution is * required to make sure the set does not contain {@code null}, because the * view cannot stop {@code null} from being added to the set. * *

Warning: This method assumes that for any instance {@code k} of * key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also * of type {@code K}. Using a key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling * methods on the resulting map view. * * @since 14.0 */ @Beta @GwtIncompatible("NavigableMap") public static NavigableMap asMap( NavigableSet set, Function function) { return new NavigableAsMapView(set, function); } private static class AsMapView extends ImprovedAbstractMap { private final Set set; final Function function; Set backingSet() { return set; } AsMapView(Set set, Function function) { this.set = checkNotNull(set); this.function = checkNotNull(function); } @Override public Set keySet() { // probably not worth caching return removeOnlySet(backingSet()); } @Override public Collection values() { // probably not worth caching return Collections2.transform(set, function); } @Override public int size() { return backingSet().size(); } @Override public boolean containsKey(@Nullable Object key) { return backingSet().contains(key); } @Override public V get(@Nullable Object key) { if (backingSet().contains(key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public V remove(@Nullable Object key) { if (backingSet().remove(key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { backingSet().clear(); } @Override protected Set> createEntrySet() { return new EntrySet() { @Override Map map() { return AsMapView.this; } @Override public Iterator> iterator() { return asSetEntryIterator(backingSet(), function); } }; } } private static Iterator> asSetEntryIterator( Set set, final Function function) { return new TransformedIterator>(set.iterator()) { @Override Entry transform(K key) { return Maps.immutableEntry(key, function.apply(key)); } }; } private static class SortedAsMapView extends AsMapView implements SortedMap { SortedAsMapView(SortedSet set, Function function) { super(set, function); } @Override SortedSet backingSet() { return (SortedSet) super.backingSet(); } @Override public Comparator comparator() { return backingSet().comparator(); } @Override public Set keySet() { return removeOnlySortedSet(backingSet()); } @Override public SortedMap subMap(K fromKey, K toKey) { return asMap(backingSet().subSet(fromKey, toKey), function); } @Override public SortedMap headMap(K toKey) { return asMap(backingSet().headSet(toKey), function); } @Override public SortedMap tailMap(K fromKey) { return asMap(backingSet().tailSet(fromKey), function); } @Override public K firstKey() { return backingSet().first(); } @Override public K lastKey() { return backingSet().last(); } } @GwtIncompatible("NavigableMap") private static final class NavigableAsMapView extends AbstractNavigableMap { /* * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the * NavigableMap methods. */ private final NavigableSet set; private final Function function; NavigableAsMapView(NavigableSet ks, Function vFunction) { this.set = checkNotNull(ks); this.function = checkNotNull(vFunction); } @Override public NavigableMap subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); } @Override public NavigableMap headMap(K toKey, boolean inclusive) { return asMap(set.headSet(toKey, inclusive), function); } @Override public NavigableMap tailMap(K fromKey, boolean inclusive) { return asMap(set.tailSet(fromKey, inclusive), function); } @Override public Comparator comparator() { return set.comparator(); } @Override @Nullable public V get(@Nullable Object key) { if (set.contains(key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { set.clear(); } @Override Iterator> entryIterator() { return asSetEntryIterator(set, function); } @Override Iterator> descendingEntryIterator() { return descendingMap().entrySet().iterator(); } @Override public NavigableSet navigableKeySet() { return removeOnlyNavigableSet(set); } @Override public int size() { return set.size(); } @Override public NavigableMap descendingMap() { return asMap(set.descendingSet(), function); } } private static Set removeOnlySet(final Set set) { return new ForwardingSet() { @Override protected Set delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection es) { throw new UnsupportedOperationException(); } }; } private static SortedSet removeOnlySortedSet(final SortedSet set) { return new ForwardingSortedSet() { @Override protected SortedSet delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection es) { throw new UnsupportedOperationException(); } @Override public SortedSet headSet(E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public SortedSet subSet(E fromElement, E toElement) { return removeOnlySortedSet(super.subSet(fromElement, toElement)); } @Override public SortedSet tailSet(E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } }; } @GwtIncompatible("NavigableSet") private static NavigableSet removeOnlyNavigableSet(final NavigableSet set) { return new ForwardingNavigableSet() { @Override protected NavigableSet delegate() { return set; } @Override public boolean add(E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection es) { throw new UnsupportedOperationException(); } @Override public SortedSet headSet(E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public SortedSet subSet(E fromElement, E toElement) { return removeOnlySortedSet( super.subSet(fromElement, toElement)); } @Override public SortedSet tailSet(E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } @Override public NavigableSet headSet(E toElement, boolean inclusive) { return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); } @Override public NavigableSet tailSet(E fromElement, boolean inclusive) { return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); } @Override public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { return removeOnlyNavigableSet(super.subSet( fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet descendingSet() { return removeOnlyNavigableSet(super.descendingSet()); } }; } /** * Returns an immutable map for which the given {@code keys} are mapped to * values by the given function in the order they appear in the original * iterable. If {@code keys} contains duplicate elements, the returned map * will contain each distinct key once in the order it first appears in * {@code keys}. * * @throws NullPointerException if any element of {@code keys} is * {@code null}, or if {@code valueFunction} produces {@code null} * for any key * @since 14.0 */ @Beta public static ImmutableMap toMap(Iterable keys, Function valueFunction) { return toMap(keys.iterator(), valueFunction); } /** * Returns an immutable map for which the given {@code keys} are mapped to * values by the given function in the order they appear in the original * iterator. If {@code keys} contains duplicate elements, the returned map * will contain each distinct key once in the order it first appears in * {@code keys}. * * @throws NullPointerException if any element of {@code keys} is * {@code null}, or if {@code valueFunction} produces {@code null} * for any key * @since 14.0 */ @Beta public static ImmutableMap toMap(Iterator keys, Function valueFunction) { checkNotNull(valueFunction); // Using LHM instead of a builder so as not to fail on duplicate keys Map builder = newLinkedHashMap(); while (keys.hasNext()) { K key = keys.next(); builder.put(key, valueFunction.apply(key)); } return ImmutableMap.copyOf(builder); } /** * Returns an immutable map for which the {@link Map#values} are the given * elements in the given order, and each key is the product of invoking a * supplied function on its corresponding value. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value */ public static ImmutableMap uniqueIndex( Iterable values, Function keyFunction) { return uniqueIndex(values.iterator(), keyFunction); } /** * Returns an immutable map for which the {@link Map#values} are the given * elements in the given order, and each key is the product of invoking a * supplied function on its corresponding value. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same * key for more than one value in the input collection * @throws NullPointerException if any elements of {@code values} is null, or * if {@code keyFunction} produces {@code null} for any value * @since 10.0 */ public static ImmutableMap uniqueIndex( Iterator values, Function keyFunction) { checkNotNull(keyFunction); ImmutableMap.Builder builder = ImmutableMap.builder(); while (values.hasNext()) { V value = values.next(); builder.put(keyFunction.apply(value), value); } return builder.build(); } /** * Creates an {@code ImmutableMap} from a {@code Properties} * instance. Properties normally derive from {@code Map}, but * they typically contain strings, which is awkward. This method lets you get * a plain-old-{@code Map} out of a {@code Properties}. * * @param properties a {@code Properties} object to be converted * @return an immutable map containing all the entries in {@code properties} * @throws ClassCastException if any key in {@code Properties} is not a {@code * String} * @throws NullPointerException if any key or value in {@code Properties} is * null */ @GwtIncompatible("java.util.Properties") public static ImmutableMap fromProperties( Properties properties) { ImmutableMap.Builder builder = ImmutableMap.builder(); for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) { String key = (String) e.nextElement(); builder.put(key, properties.getProperty(key)); } return builder.build(); } /** * Returns an immutable map entry with the specified key and value. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * *

The returned entry is serializable. * * @param key the key to be associated with the returned entry * @param value the value to be associated with the returned entry */ @GwtCompatible(serializable = true) public static Entry immutableEntry( @Nullable K key, @Nullable V value) { return new ImmutableEntry(key, value); } /** * Returns an unmodifiable view of the specified set of entries. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}, * as do any operations that would modify the returned set. * * @param entrySet the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ static Set> unmodifiableEntrySet( Set> entrySet) { return new UnmodifiableEntrySet( Collections.unmodifiableSet(entrySet)); } /** * Returns an unmodifiable view of the specified map entry. The {@link * Entry#setValue} operation throws an {@link UnsupportedOperationException}. * This also has the side-effect of redefining {@code equals} to comply with * the Entry contract, to avoid a possible nefarious implementation of equals. * * @param entry the entry for which to return an unmodifiable view * @return an unmodifiable view of the entry */ static Entry unmodifiableEntry(final Entry entry) { checkNotNull(entry); return new AbstractMapEntry() { @Override public K getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue(); } }; } /** @see Multimaps#unmodifiableEntries */ static class UnmodifiableEntries extends ForwardingCollection> { private final Collection> entries; UnmodifiableEntries(Collection> entries) { this.entries = entries; } @Override protected Collection> delegate() { return entries; } @Override public Iterator> iterator() { final Iterator> delegate = super.iterator(); return new ForwardingIterator>() { @Override public Entry next() { return unmodifiableEntry(super.next()); } @Override public void remove() { throw new UnsupportedOperationException(); } @Override protected Iterator> delegate() { return delegate; } }; } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public boolean add(Entry element) { throw new UnsupportedOperationException(); } @Override public boolean addAll( Collection> collection) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean remove(Object object) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection collection) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection collection) { throw new UnsupportedOperationException(); } @Override public Object[] toArray() { return standardToArray(); } @Override public T[] toArray(T[] array) { return standardToArray(array); } } /** @see Maps#unmodifiableEntrySet(Set) */ static class UnmodifiableEntrySet extends UnmodifiableEntries implements Set> { UnmodifiableEntrySet(Set> entries) { super(entries); } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public boolean equals(@Nullable Object object) { return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } } /** * Returns a synchronized (thread-safe) bimap backed by the specified bimap. * In order to guarantee serial access, it is critical that all access * to the backing bimap is accomplished through the returned bimap. * *

It is imperative that the user manually synchronize on the returned map * when accessing any of its collection views:

   {@code
   *
   *   BiMap map = Maps.synchronizedBiMap(
   *       HashBiMap.create());
   *   ...
   *   Set set = map.keySet();  // Needn't be in synchronized block
   *   ...
   *   synchronized (map) {  // Synchronizing on map, not set!
   *     Iterator it = set.iterator(); // Must be in synchronized block
   *     while (it.hasNext()) {
   *       foo(it.next());
   *     }
   *   }}
* * Failure to follow this advice may result in non-deterministic behavior. * *

The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap to be wrapped in a synchronized view * @return a sychronized view of the specified bimap */ public static BiMap synchronizedBiMap(BiMap bimap) { return Synchronized.biMap(bimap, null); } /** * Returns an unmodifiable view of the specified bimap. This method allows * modules to provide users with "read-only" access to internal bimaps. Query * operations on the returned bimap "read through" to the specified bimap, and * attempts to modify the returned map, whether direct or via its collection * views, result in an {@code UnsupportedOperationException}. * *

The returned bimap will be serializable if the specified bimap is * serializable. * * @param bimap the bimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified bimap */ public static BiMap unmodifiableBiMap( BiMap bimap) { return new UnmodifiableBiMap(bimap, null); } /** @see Maps#unmodifiableBiMap(BiMap) */ private static class UnmodifiableBiMap extends ForwardingMap implements BiMap, Serializable { final Map unmodifiableMap; final BiMap delegate; BiMap inverse; transient Set values; UnmodifiableBiMap(BiMap delegate, @Nullable BiMap inverse) { unmodifiableMap = Collections.unmodifiableMap(delegate); this.delegate = delegate; this.inverse = inverse; } @Override protected Map delegate() { return unmodifiableMap; } @Override public V forcePut(K key, V value) { throw new UnsupportedOperationException(); } @Override public BiMap inverse() { BiMap result = inverse; return (result == null) ? inverse = new UnmodifiableBiMap(delegate.inverse(), this) : result; } @Override public Set values() { Set result = values; return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; } private static final long serialVersionUID = 0; } /** * Returns a view of a map where each value is transformed by a function. All * other properties of the map, such as iteration order, are left intact. For * example, the code:

   {@code
   *
   *   Map map = ImmutableMap.of("a", 4, "b", 9);
   *   Function sqrt =
   *       new Function() {
   *         public Double apply(Integer in) {
   *           return Math.sqrt((int) in);
   *         }
   *       };
   *   Map transformed = Maps.transformValues(map, sqrt);
   *   System.out.println(transformed);}
* * ... prints {@code {a=2.0, b=3.0}}. * *

Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * *

It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. */ public static Map transformValues( Map fromMap, Function function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a sorted map where each value is transformed by a * function. All other properties of the map, such as iteration order, are * left intact. For example, the code:

   {@code
   *
   *   SortedMap map = ImmutableSortedMap.of("a", 4, "b", 9);
   *   Function sqrt =
   *       new Function() {
   *         public Double apply(Integer in) {
   *           return Math.sqrt((int) in);
   *         }
   *       };
   *   SortedMap transformed =
   *        Maps.transformSortedValues(map, sqrt);
   *   System.out.println(transformed);}
* * ... prints {@code {a=2.0, b=3.0}}. * *

Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * *

It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. * * @since 11.0 */ public static SortedMap transformValues( SortedMap fromMap, Function function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a navigable map where each value is transformed by a * function. All other properties of the map, such as iteration order, are * left intact. For example, the code:

   {@code
   *
   *   NavigableMap map = Maps.newTreeMap();
   *   map.put("a", 4);
   *   map.put("b", 9);
   *   Function sqrt =
   *       new Function() {
   *         public Double apply(Integer in) {
   *           return Math.sqrt((int) in);
   *         }
   *       };
   *   NavigableMap transformed =
   *        Maps.transformNavigableValues(map, sqrt);
   *   System.out.println(transformed);}
* * ... prints {@code {a=2.0, b=3.0}}. * * Changes in the underlying map are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying map. * *

It's acceptable for the underlying map to contain null keys, and even * null values provided that the function is capable of accepting null input. * The transformed map might contain null values, if the function sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The function is applied lazily, invoked when needed. This is necessary * for the returned map to be a view, but it means that the function will be * applied many times for bulk operations like {@link Map#containsValue} and * {@code Map.toString()}. For this to perform well, {@code function} should * be fast. To avoid lazy evaluation when the returned map doesn't need to be * a view, copy the returned map into a new map of your choosing. * * @since 13.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap transformValues( NavigableMap fromMap, Function function) { return transformEntries(fromMap, asEntryTransformer(function)); } private static EntryTransformer asEntryTransformer(final Function function) { checkNotNull(function); return new EntryTransformer() { @Override public V2 transformEntry(K key, V1 value) { return function.apply(value); } }; } /** * Returns a view of a map whose values are derived from the original map's * entries. In contrast to {@link #transformValues}, this method's * entry-transformation logic may depend on the key as well as the value. * *

All other properties of the transformed map, such as iteration order, * are left intact. For example, the code:

   {@code
   *
   *   Map options =
   *       ImmutableMap.of("verbose", true, "sort", false);
   *   EntryTransformer flagPrefixer =
   *       new EntryTransformer() {
   *         public String transformEntry(String key, Boolean value) {
   *           return value ? key : "no" + key;
   *         }
   *       };
   *   Map transformed =
   *       Maps.transformEntries(options, flagPrefixer);
   *   System.out.println(transformed);}
* * ... prints {@code {verbose=verbose, sort=nosort}}. * *

Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * *

It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * *

Warning: This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @since 7.0 */ public static Map transformEntries( Map fromMap, EntryTransformer transformer) { if (fromMap instanceof SortedMap) { return transformEntries((SortedMap) fromMap, transformer); } return new TransformedEntriesMap(fromMap, transformer); } /** * Returns a view of a sorted map whose values are derived from the original * sorted map's entries. In contrast to {@link #transformValues}, this * method's entry-transformation logic may depend on the key as well as the * value. * *

All other properties of the transformed map, such as iteration order, * are left intact. For example, the code:

   {@code
   *
   *   Map options =
   *       ImmutableSortedMap.of("verbose", true, "sort", false);
   *   EntryTransformer flagPrefixer =
   *       new EntryTransformer() {
   *         public String transformEntry(String key, Boolean value) {
   *           return value ? key : "yes" + key;
   *         }
   *       };
   *   SortedMap transformed =
   *       LabsMaps.transformSortedEntries(options, flagPrefixer);
   *   System.out.println(transformed);}
* * ... prints {@code {sort=yessort, verbose=verbose}}. * *

Changes in the underlying map are reflected in this view. Conversely, * this view supports removal operations, and these are reflected in the * underlying map. * *

It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * *

Warning: This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @since 11.0 */ public static SortedMap transformEntries( SortedMap fromMap, EntryTransformer transformer) { return Platform.mapsTransformEntriesSortedMap(fromMap, transformer); } /** * Returns a view of a navigable map whose values are derived from the * original navigable map's entries. In contrast to {@link * #transformValues}, this method's entry-transformation logic may * depend on the key as well as the value. * *

All other properties of the transformed map, such as iteration order, * are left intact. For example, the code:

   {@code
   *
   *   NavigableMap options = Maps.newTreeMap();
   *   options.put("verbose", false);
   *   options.put("sort", true);
   *   EntryTransformer flagPrefixer =
   *       new EntryTransformer() {
   *         public String transformEntry(String key, Boolean value) {
   *           return value ? key : ("yes" + key);
   *         }
   *       };
   *   NavigableMap transformed =
   *       LabsMaps.transformNavigableEntries(options, flagPrefixer);
   *   System.out.println(transformed);}
* * ... prints {@code {sort=yessort, verbose=verbose}}. * *

Changes in the underlying map are reflected in this view. * Conversely, this view supports removal operations, and these are reflected * in the underlying map. * *

It's acceptable for the underlying map to contain null keys and null * values provided that the transformer is capable of accepting null inputs. * The transformed map might contain null values if the transformer sometimes * gives a null result. * *

The returned map is not thread-safe or serializable, even if the * underlying map is. * *

The transformer is applied lazily, invoked when needed. This is * necessary for the returned map to be a view, but it means that the * transformer will be applied many times for bulk operations like {@link * Map#containsValue} and {@link Object#toString}. For this to perform well, * {@code transformer} should be fast. To avoid lazy evaluation when the * returned map doesn't need to be a view, copy the returned map into a new * map of your choosing. * *

Warning: This method assumes that for any instance {@code k} of * {@code EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies * that {@code k2} is also of type {@code K}. Using an {@code * EntryTransformer} key type for which this may not hold, such as {@code * ArrayList}, may risk a {@code ClassCastException} when calling methods on * the transformed map. * * @since 13.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap transformEntries( final NavigableMap fromMap, EntryTransformer transformer) { return new TransformedEntriesNavigableMap(fromMap, transformer); } static SortedMap transformEntriesIgnoreNavigable( SortedMap fromMap, EntryTransformer transformer) { return new TransformedEntriesSortedMap(fromMap, transformer); } /** * A transformation of the value of a key-value pair, using both key and value * as inputs. To apply the transformation to a map, use * {@link Maps#transformEntries(Map, EntryTransformer)}. * * @param the key type of the input and output entries * @param the value type of the input entry * @param the value type of the output entry * @since 7.0 */ public interface EntryTransformer { /** * Determines an output value based on a key-value pair. This method is * generally expected, but not absolutely required, to have the * following properties: * *

    *
  • Its execution does not cause any observable side effects. *
  • The computation is consistent with equals; that is, * {@link Objects#equal Objects.equal}{@code (k1, k2) &&} * {@link Objects#equal}{@code (v1, v2)} implies that {@code * Objects.equal(transformer.transform(k1, v1), * transformer.transform(k2, v2))}. *
* * @throws NullPointerException if the key or value is null and this * transformer does not accept null arguments */ V2 transformEntry(@Nullable K key, @Nullable V1 value); } static class TransformedEntriesMap extends AbstractMap { final Map fromMap; final EntryTransformer transformer; TransformedEntriesMap( Map fromMap, EntryTransformer transformer) { this.fromMap = checkNotNull(fromMap); this.transformer = checkNotNull(transformer); } @Override public int size() { return fromMap.size(); } @Override public boolean containsKey(Object key) { return fromMap.containsKey(key); } // safe as long as the user followed the Warning in the javadoc @SuppressWarnings("unchecked") @Override public V2 get(Object key) { V1 value = fromMap.get(key); return (value != null || fromMap.containsKey(key)) ? transformer.transformEntry((K) key, value) : null; } // safe as long as the user followed the Warning in the javadoc @SuppressWarnings("unchecked") @Override public V2 remove(Object key) { return fromMap.containsKey(key) ? transformer.transformEntry((K) key, fromMap.remove(key)) : null; } @Override public void clear() { fromMap.clear(); } @Override public Set keySet() { return fromMap.keySet(); } Set> entrySet; @Override public Set> entrySet() { Set> result = entrySet; if (result == null) { entrySet = result = new EntrySet() { @Override Map map() { return TransformedEntriesMap.this; } @Override public Iterator> iterator() { return new TransformedIterator, Entry>( fromMap.entrySet().iterator()) { @Override Entry transform(final Entry entry) { return new AbstractMapEntry() { @Override public K getKey() { return entry.getKey(); } @Override public V2 getValue() { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; } }; } }; } return result; } Collection values; @Override public Collection values() { Collection result = values; if (result == null) { return values = new Values() { @Override Map map() { return TransformedEntriesMap.this; } }; } return result; } } static class TransformedEntriesSortedMap extends TransformedEntriesMap implements SortedMap { protected SortedMap fromMap() { return (SortedMap) fromMap; } TransformedEntriesSortedMap(SortedMap fromMap, EntryTransformer transformer) { super(fromMap, transformer); } @Override public Comparator comparator() { return fromMap().comparator(); } @Override public K firstKey() { return fromMap().firstKey(); } @Override public SortedMap headMap(K toKey) { return transformEntries(fromMap().headMap(toKey), transformer); } @Override public K lastKey() { return fromMap().lastKey(); } @Override public SortedMap subMap(K fromKey, K toKey) { return transformEntries( fromMap().subMap(fromKey, toKey), transformer); } @Override public SortedMap tailMap(K fromKey) { return transformEntries(fromMap().tailMap(fromKey), transformer); } } @GwtIncompatible("NavigableMap") private static class TransformedEntriesNavigableMap extends TransformedEntriesSortedMap implements NavigableMap { TransformedEntriesNavigableMap(NavigableMap fromMap, EntryTransformer transformer) { super(fromMap, transformer); } @Override public Entry ceilingEntry(K key) { return transformEntry(fromMap().ceilingEntry(key)); } @Override public K ceilingKey(K key) { return fromMap().ceilingKey(key); } @Override public NavigableSet descendingKeySet() { return fromMap().descendingKeySet(); } @Override public NavigableMap descendingMap() { return transformEntries(fromMap().descendingMap(), transformer); } @Override public Entry firstEntry() { return transformEntry(fromMap().firstEntry()); } @Override public Entry floorEntry(K key) { return transformEntry(fromMap().floorEntry(key)); } @Override public K floorKey(K key) { return fromMap().floorKey(key); } @Override public NavigableMap headMap(K toKey) { return headMap(toKey, false); } @Override public NavigableMap headMap(K toKey, boolean inclusive) { return transformEntries( fromMap().headMap(toKey, inclusive), transformer); } @Override public Entry higherEntry(K key) { return transformEntry(fromMap().higherEntry(key)); } @Override public K higherKey(K key) { return fromMap().higherKey(key); } @Override public Entry lastEntry() { return transformEntry(fromMap().lastEntry()); } @Override public Entry lowerEntry(K key) { return transformEntry(fromMap().lowerEntry(key)); } @Override public K lowerKey(K key) { return fromMap().lowerKey(key); } @Override public NavigableSet navigableKeySet() { return fromMap().navigableKeySet(); } @Override public Entry pollFirstEntry() { return transformEntry(fromMap().pollFirstEntry()); } @Override public Entry pollLastEntry() { return transformEntry(fromMap().pollLastEntry()); } @Override public NavigableMap subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return transformEntries( fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); } @Override public NavigableMap subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap tailMap(K fromKey, boolean inclusive) { return transformEntries( fromMap().tailMap(fromKey, inclusive), transformer); } private Entry transformEntry(Entry entry) { if (entry == null) { return null; } K key = entry.getKey(); V2 v2 = transformer.transformEntry(key, entry.getValue()); return Maps.immutableEntry(key, v2); } @Override protected NavigableMap fromMap() { return (NavigableMap) super.fromMap(); } } private static final class KeyPredicate implements Predicate> { private final Predicate keyPredicate; KeyPredicate(Predicate keyPredicate) { this.keyPredicate = checkNotNull(keyPredicate); } @Override public boolean apply(Entry input) { return keyPredicate.apply(input.getKey()); } } private static final class ValuePredicate implements Predicate> { private final Predicate valuePredicate; ValuePredicate(Predicate valuePredicate) { this.valuePredicate = checkNotNull(valuePredicate); } @Override public boolean apply(Entry input) { return valuePredicate.apply(input.getValue()); } } /** * Returns a map containing the mappings in {@code unfiltered} whose keys * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code keyPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static Map filterKeys( Map unfiltered, final Predicate keyPredicate) { if (unfiltered instanceof SortedMap) { return filterKeys((SortedMap) unfiltered, keyPredicate); } else if (unfiltered instanceof BiMap) { return filterKeys((BiMap) unfiltered, keyPredicate); } checkNotNull(keyPredicate); Predicate> entryPredicate = new KeyPredicate(keyPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap) unfiltered, entryPredicate) : new FilteredKeyMap( checkNotNull(unfiltered), keyPredicate, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code keyPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ public static SortedMap filterKeys( SortedMap unfiltered, final Predicate keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, new KeyPredicate(keyPredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose * keys satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a key that * doesn't satisfy the predicate, the map's {@code put()} and {@code putAll()} * methods throw an {@link IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose keys satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code keyPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap filterKeys( NavigableMap unfiltered, final Predicate keyPredicate) { // TODO(user): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, new KeyPredicate(keyPredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate. * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * *

The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the * bimap and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * *

The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * *

Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in * the underlying bimap and determine which satisfy the filter. When a live view is not * needed, it may be faster to copy the filtered bimap and use the copy. * *

Warning: {@code entryPredicate} must be consistent with equals , as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static BiMap filterKeys( BiMap unfiltered, final Predicate keyPredicate) { checkNotNull(keyPredicate); return filterEntries(unfiltered, new KeyPredicate(keyPredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} whose values * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code valuePredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. */ public static Map filterValues( Map unfiltered, final Predicate valuePredicate) { if (unfiltered instanceof SortedMap) { return filterValues((SortedMap) unfiltered, valuePredicate); } else if (unfiltered instanceof BiMap) { return filterValues((BiMap) unfiltered, valuePredicate); } return filterEntries(unfiltered, new ValuePredicate(valuePredicate)); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code valuePredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 11.0 */ public static SortedMap filterValues( SortedMap unfiltered, final Predicate valuePredicate) { return filterEntries(unfiltered, new ValuePredicate(valuePredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose * values satisfy a predicate. The returned map is a live view of {@code * unfiltered}; changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a value * that doesn't satisfy the predicate, the map's {@code put()}, {@code * putAll()}, and {@link Entry#setValue} methods throw an {@link * IllegalArgumentException}. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings whose values satisfy the * filter will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code valuePredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. Do not provide a * predicate such as {@code Predicates.instanceOf(ArrayList.class)}, which is * inconsistent with equals. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap filterValues( NavigableMap unfiltered, final Predicate valuePredicate) { return filterEntries(unfiltered, new ValuePredicate(valuePredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned bimap is a live view of {@code unfiltered}; changes to one affect the * other. * *

The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the * bimap and its views. When given a value that doesn't satisfy the predicate, the bimap's * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the * predicate. * *

When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * *

The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * *

Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in * the underlying bimap and determine which satisfy the filter. When a live view is not * needed, it may be faster to copy the filtered bimap and use the copy. * *

Warning: {@code entryPredicate} must be consistent with equals , as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static BiMap filterValues( BiMap unfiltered, final Predicate valuePredicate) { return filterEntries(unfiltered, new ValuePredicate(valuePredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} that satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes * to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code entryPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. */ public static Map filterEntries( Map unfiltered, Predicate> entryPredicate) { if (unfiltered instanceof SortedMap) { return filterEntries((SortedMap) unfiltered, entryPredicate); } else if (unfiltered instanceof BiMap) { return filterEntries((BiMap) unfiltered, entryPredicate); } checkNotNull(entryPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap) unfiltered, entryPredicate) : new FilteredEntryMap(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code entryPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. * * @since 11.0 */ public static SortedMap filterEntries( SortedMap unfiltered, Predicate> entryPredicate) { return Platform.mapsFilterSortedMap(unfiltered, entryPredicate); } static SortedMap filterSortedIgnoreNavigable( SortedMap unfiltered, Predicate> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntrySortedMap) ? filterFiltered((FilteredEntrySortedMap) unfiltered, entryPredicate) : new FilteredEntrySortedMap(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that * satisfy a predicate. The returned map is a live view of {@code unfiltered}; * changes to one affect the other. * *

The resulting map's {@code keySet()}, {@code entrySet()}, and {@code * values()} views have iterators that don't support {@code remove()}, but all * other methods are supported by the map and its views. When given a * key/value pair that doesn't satisfy the predicate, the map's {@code put()} * and {@code putAll()} methods throw an {@link IllegalArgumentException}. * Similarly, the map's entries have a {@link Entry#setValue} method that * throws an {@link IllegalArgumentException} when the existing key and the * provided value don't satisfy the predicate. * *

When methods such as {@code removeAll()} and {@code clear()} are called * on the filtered map or its views, only mappings that satisfy the filter * will be removed from the underlying map. * *

The returned map isn't threadsafe or serializable, even if {@code * unfiltered} is. * *

Many of the filtered map's methods, such as {@code size()}, * iterate across every key/value mapping in the underlying map and determine * which satisfy the filter. When a live view is not needed, it may be * faster to copy the filtered map and use the copy. * *

Warning: {@code entryPredicate} must be consistent with * equals, as documented at {@link Predicate#apply}. * * @since 14.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap filterEntries( NavigableMap unfiltered, Predicate> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryNavigableMap) ? filterFiltered((FilteredEntryNavigableMap) unfiltered, entryPredicate) : new FilteredEntryNavigableMap(checkNotNull(unfiltered), entryPredicate); } /** * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * *

The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the bimap * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an * {@link IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} * method that throws an {@link IllegalArgumentException} when the existing key and the provided * value don't satisfy the predicate. * *

When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * *

The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * *

Many of the filtered bimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying bimap and determine which satisfy the filter. When a live * view is not needed, it may be faster to copy the filtered bimap and use the copy. * *

Warning: {@code entryPredicate} must be consistent with equals , as * documented at {@link Predicate#apply}. * * @since 14.0 */ public static BiMap filterEntries( BiMap unfiltered, Predicate> entryPredicate) { checkNotNull(unfiltered); checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryBiMap) ? filterFiltered((FilteredEntryBiMap) unfiltered, entryPredicate) : new FilteredEntryBiMap(unfiltered, entryPredicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered map. */ private static Map filterFiltered(AbstractFilteredMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntryMap(map.unfiltered, predicate); } private abstract static class AbstractFilteredMap extends AbstractMap { final Map unfiltered; final Predicate> predicate; AbstractFilteredMap( Map unfiltered, Predicate> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } boolean apply(Object key, V value) { // This method is called only when the key is in the map, implying that // key is a K. @SuppressWarnings("unchecked") K k = (K) key; return predicate.apply(Maps.immutableEntry(k, value)); } @Override public V put(K key, V value) { checkArgument(apply(key, value)); return unfiltered.put(key, value); } @Override public void putAll(Map map) { for (Entry entry : map.entrySet()) { checkArgument(apply(entry.getKey(), entry.getValue())); } unfiltered.putAll(map); } @Override public boolean containsKey(Object key) { return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); } @Override public V get(Object key) { V value = unfiltered.get(key); return ((value != null) && apply(key, value)) ? value : null; } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public V remove(Object key) { return containsKey(key) ? unfiltered.remove(key) : null; } Collection values; @Override public Collection values() { Collection result = values; return (result == null) ? values = new Values() : result; } class Values extends AbstractCollection { @Override public Iterator iterator() { final Iterator> entryIterator = entrySet().iterator(); return new UnmodifiableIterator() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public V next() { return entryIterator.next().getValue(); } }; } @Override public int size() { return entrySet().size(); } @Override public void clear() { entrySet().clear(); } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override public boolean remove(Object o) { Iterator> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); if (Objects.equal(o, entry.getValue()) && predicate.apply(entry)) { iterator.remove(); return true; } } return false; } @Override public boolean removeAll(Collection collection) { checkNotNull(collection); boolean changed = false; Iterator> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); if (collection.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public boolean retainAll(Collection collection) { checkNotNull(collection); boolean changed = false; Iterator> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); if (!collection.contains(entry.getValue()) && predicate.apply(entry)) { iterator.remove(); changed = true; } } return changed; } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered sorted map. */ private static SortedMap filterFiltered( FilteredEntrySortedMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntrySortedMap(map.sortedMap(), predicate); } private static class FilteredEntrySortedMap extends FilteredEntryMap implements SortedMap { FilteredEntrySortedMap(SortedMap unfiltered, Predicate> entryPredicate) { super(unfiltered, entryPredicate); } SortedMap sortedMap() { return (SortedMap) unfiltered; } @Override public Comparator comparator() { return sortedMap().comparator(); } @Override public K firstKey() { // correctly throws NoSuchElementException when filtered map is empty. return keySet().iterator().next(); } @Override public K lastKey() { SortedMap headMap = sortedMap(); while (true) { // correctly throws NoSuchElementException when filtered map is empty. K key = headMap.lastKey(); if (apply(key, unfiltered.get(key))) { return key; } headMap = sortedMap().headMap(key); } } @Override public SortedMap headMap(K toKey) { return new FilteredEntrySortedMap(sortedMap().headMap(toKey), predicate); } @Override public SortedMap subMap(K fromKey, K toKey) { return new FilteredEntrySortedMap( sortedMap().subMap(fromKey, toKey), predicate); } @Override public SortedMap tailMap(K fromKey) { return new FilteredEntrySortedMap( sortedMap().tailMap(fromKey), predicate); } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered navigable map. */ @GwtIncompatible("NavigableMap") private static NavigableMap filterFiltered( FilteredEntryNavigableMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntryNavigableMap(map.sortedMap(), predicate); } @GwtIncompatible("NavigableMap") private static class FilteredEntryNavigableMap extends FilteredEntrySortedMap implements NavigableMap { FilteredEntryNavigableMap( NavigableMap unfiltered, Predicate> entryPredicate) { super(unfiltered, entryPredicate); } @Override NavigableMap sortedMap() { return (NavigableMap) super.sortedMap(); } @Override public Entry lowerEntry(K key) { return headMap(key, false).lastEntry(); } @Override public K lowerKey(K key) { return keyOrNull(lowerEntry(key)); } @Override public Entry floorEntry(K key) { return headMap(key, true).lastEntry(); } @Override public K floorKey(K key) { return keyOrNull(floorEntry(key)); } @Override public Entry ceilingEntry(K key) { return tailMap(key, true).firstEntry(); } @Override public K ceilingKey(K key) { return keyOrNull(ceilingEntry(key)); } @Override public Entry higherEntry(K key) { return tailMap(key, false).firstEntry(); } @Override public K higherKey(K key) { return keyOrNull(higherEntry(key)); } @Override public Entry firstEntry() { return Iterables.getFirst(entrySet(), null); } @Override public Entry lastEntry() { return Iterables.getFirst(descendingMap().entrySet(), null); } @Override public Entry pollFirstEntry() { return pollFirstSatisfyingEntry(sortedMap().entrySet().iterator()); } @Override public Entry pollLastEntry() { return pollFirstSatisfyingEntry(sortedMap().descendingMap().entrySet().iterator()); } @Nullable Entry pollFirstSatisfyingEntry(Iterator> entryIterator) { while (entryIterator.hasNext()) { Entry entry = entryIterator.next(); if (predicate.apply(entry)) { entryIterator.remove(); return entry; } } return null; } @Override public NavigableMap descendingMap() { return filterEntries(sortedMap().descendingMap(), predicate); } @Override public NavigableSet keySet() { return (NavigableSet) super.keySet(); } @Override NavigableSet createKeySet() { return new NavigableKeySet(this) { @Override public boolean removeAll(Collection c) { boolean changed = false; Iterator> entryIterator = sortedMap().entrySet().iterator(); while (entryIterator.hasNext()) { Entry entry = entryIterator.next(); if (c.contains(entry.getKey()) && predicate.apply(entry)) { entryIterator.remove(); changed = true; } } return changed; } @Override public boolean retainAll(Collection c) { boolean changed = false; Iterator> entryIterator = sortedMap().entrySet().iterator(); while (entryIterator.hasNext()) { Entry entry = entryIterator.next(); if (!c.contains(entry.getKey()) && predicate.apply(entry)) { entryIterator.remove(); changed = true; } } return changed; } }; } @Override public NavigableSet navigableKeySet() { return keySet(); } @Override public NavigableSet descendingKeySet() { return descendingMap().navigableKeySet(); } @Override public NavigableMap subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return filterEntries( sortedMap().subMap(fromKey, fromInclusive, toKey, toInclusive), predicate); } @Override public NavigableMap headMap(K toKey) { return headMap(toKey, false); } @Override public NavigableMap headMap(K toKey, boolean inclusive) { return filterEntries(sortedMap().headMap(toKey, inclusive), predicate); } @Override public NavigableMap tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap tailMap(K fromKey, boolean inclusive) { return filterEntries(sortedMap().tailMap(fromKey, inclusive), predicate); } } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when * filtering a filtered map. */ private static BiMap filterFiltered( FilteredEntryBiMap map, Predicate> entryPredicate) { Predicate> predicate = Predicates.and(map.predicate, entryPredicate); return new FilteredEntryBiMap(map.unfiltered(), predicate); } static final class FilteredEntryBiMap extends FilteredEntryMap implements BiMap { private final BiMap inverse; private static Predicate> inversePredicate( final Predicate> forwardPredicate) { return new Predicate>() { @Override public boolean apply(Entry input) { return forwardPredicate.apply( Maps.immutableEntry(input.getValue(), input.getKey())); } }; } FilteredEntryBiMap(BiMap delegate, Predicate> predicate) { super(delegate, predicate); this.inverse = new FilteredEntryBiMap( delegate.inverse(), inversePredicate(predicate), this); } private FilteredEntryBiMap( BiMap delegate, Predicate> predicate, BiMap inverse) { super(delegate, predicate); this.inverse = inverse; } BiMap unfiltered() { return (BiMap) unfiltered; } @Override public V forcePut(@Nullable K key, @Nullable V value) { checkArgument(predicate.apply(Maps.immutableEntry(key, value))); return unfiltered().forcePut(key, value); } @Override public BiMap inverse() { return inverse; } @Override public Set values() { return inverse.keySet(); } } private static class FilteredKeyMap extends AbstractFilteredMap { Predicate keyPredicate; FilteredKeyMap(Map unfiltered, Predicate keyPredicate, Predicate> entryPredicate) { super(unfiltered, entryPredicate); this.keyPredicate = keyPredicate; } Set> entrySet; @Override public Set> entrySet() { Set> result = entrySet; return (result == null) ? entrySet = Sets.filter(unfiltered.entrySet(), predicate) : result; } Set keySet; @Override public Set keySet() { Set result = keySet; return (result == null) ? keySet = Sets.filter(unfiltered.keySet(), keyPredicate) : result; } // The cast is called only when the key is in the unfiltered map, implying // that key is a K. @Override @SuppressWarnings("unchecked") public boolean containsKey(Object key) { return unfiltered.containsKey(key) && keyPredicate.apply((K) key); } } static class FilteredEntryMap extends AbstractFilteredMap { /** * Entries in this set satisfy the predicate, but they don't validate the * input to {@code Entry.setValue()}. */ final Set> filteredEntrySet; FilteredEntryMap( Map unfiltered, Predicate> entryPredicate) { super(unfiltered, entryPredicate); filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); } Set> entrySet; @Override public Set> entrySet() { Set> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends ForwardingSet> { @Override protected Set> delegate() { return filteredEntrySet; } @Override public Iterator> iterator() { final Iterator> iterator = filteredEntrySet.iterator(); return new UnmodifiableIterator>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry next() { final Entry entry = iterator.next(); return new ForwardingMapEntry() { @Override protected Entry delegate() { return entry; } @Override public V setValue(V value) { checkArgument(apply(entry.getKey(), value)); return super.setValue(value); } }; } }; } } Set keySet; @Override public Set keySet() { Set result = keySet; return (result == null) ? keySet = createKeySet() : result; } Set createKeySet() { return new KeySet(); } private class KeySet extends Sets.ImprovedAbstractSet { @Override public Iterator iterator() { final Iterator> iterator = filteredEntrySet.iterator(); return new UnmodifiableIterator() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { return iterator.next().getKey(); } }; } @Override public int size() { return filteredEntrySet.size(); } @Override public void clear() { filteredEntrySet.clear(); } @Override public boolean contains(Object o) { return containsKey(o); } @Override public boolean remove(Object o) { if (containsKey(o)) { unfiltered.remove(o); return true; } return false; } @Override public boolean retainAll(Collection collection) { checkNotNull(collection); // for GWT boolean changed = false; Iterator> iterator = unfiltered.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = iterator.next(); if (predicate.apply(entry) && !collection.contains(entry.getKey())) { iterator.remove(); changed = true; } } return changed; } @Override public Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override public T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } /** * Returns an unmodifiable view of the specified navigable map. Query operations on the returned * map read through to the specified map, and attempts to modify the returned map, whether direct * or via its views, result in an {@code UnsupportedOperationException}. * *

The returned navigable map will be serializable if the specified navigable map is * serializable. * * @param map the navigable map for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified navigable map * @since 12.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap unmodifiableNavigableMap(NavigableMap map) { checkNotNull(map); if (map instanceof UnmodifiableNavigableMap) { return map; } else { return new UnmodifiableNavigableMap(map); } } @Nullable private static Entry unmodifiableOrNull(@Nullable Entry entry) { return (entry == null) ? null : Maps.unmodifiableEntry(entry); } @GwtIncompatible("NavigableMap") static class UnmodifiableNavigableMap extends ForwardingSortedMap implements NavigableMap, Serializable { private final NavigableMap delegate; UnmodifiableNavigableMap(NavigableMap delegate) { this.delegate = delegate; } @Override protected SortedMap delegate() { return Collections.unmodifiableSortedMap(delegate); } @Override public Entry lowerEntry(K key) { return unmodifiableOrNull(delegate.lowerEntry(key)); } @Override public K lowerKey(K key) { return delegate.lowerKey(key); } @Override public Entry floorEntry(K key) { return unmodifiableOrNull(delegate.floorEntry(key)); } @Override public K floorKey(K key) { return delegate.floorKey(key); } @Override public Entry ceilingEntry(K key) { return unmodifiableOrNull(delegate.ceilingEntry(key)); } @Override public K ceilingKey(K key) { return delegate.ceilingKey(key); } @Override public Entry higherEntry(K key) { return unmodifiableOrNull(delegate.higherEntry(key)); } @Override public K higherKey(K key) { return delegate.higherKey(key); } @Override public Entry firstEntry() { return unmodifiableOrNull(delegate.firstEntry()); } @Override public Entry lastEntry() { return unmodifiableOrNull(delegate.lastEntry()); } @Override public final Entry pollFirstEntry() { throw new UnsupportedOperationException(); } @Override public final Entry pollLastEntry() { throw new UnsupportedOperationException(); } private transient UnmodifiableNavigableMap descendingMap; @Override public NavigableMap descendingMap() { UnmodifiableNavigableMap result = descendingMap; if (result == null) { descendingMap = result = new UnmodifiableNavigableMap(delegate.descendingMap()); result.descendingMap = this; } return result; } @Override public Set keySet() { return navigableKeySet(); } @Override public NavigableSet navigableKeySet() { return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); } @Override public NavigableSet descendingKeySet() { return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); } @Override public SortedMap subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return Maps.unmodifiableNavigableMap(delegate.subMap( fromKey, fromInclusive, toKey, toInclusive)); } @Override public NavigableMap headMap(K toKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); } @Override public NavigableMap tailMap(K fromKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); } } /** * Returns a synchronized (thread-safe) navigable map backed by the specified * navigable map. In order to guarantee serial access, it is critical that * all access to the backing navigable map is accomplished * through the returned navigable map (or its views). * *

It is imperative that the user manually synchronize on the returned * navigable map when iterating over any of its collection views, or the * collections views of any of its {@code descendingMap}, {@code subMap}, * {@code headMap} or {@code tailMap} views.

   {@code
   *
   *   NavigableMap map = synchronizedNavigableMap(new TreeMap());
   *
   *   // Needn't be in synchronized block
   *   NavigableSet set = map.navigableKeySet();
   *
   *   synchronized (map) { // Synchronizing on map, not set!
   *     Iterator it = set.iterator(); // Must be in synchronized block
   *     while (it.hasNext()){
   *       foo(it.next());
   *     }
   *   }}
* * or:
   {@code
   *
   *   NavigableMap map = synchronizedNavigableMap(new TreeMap());
   *   NavigableMap map2 = map.subMap(foo, false, bar, true);
   *
   *   // Needn't be in synchronized block
   *   NavigableSet set2 = map2.descendingKeySet();
   *
   *   synchronized (map) { // Synchronizing on map, not map2 or set2!
   *     Iterator it = set2.iterator(); // Must be in synchronized block
   *     while (it.hasNext()){
   *       foo(it.next());
   *     }
   *   }}
* * Failure to follow this advice may result in non-deterministic behavior. * *

The returned navigable map will be serializable if the specified * navigable map is serializable. * * @param navigableMap the navigable map to be "wrapped" in a synchronized * navigable map. * @return a synchronized view of the specified navigable map. * @since 13.0 */ @GwtIncompatible("NavigableMap") public static NavigableMap synchronizedNavigableMap( NavigableMap navigableMap) { return Synchronized.navigableMap(navigableMap); } /** * {@code AbstractMap} extension that implements {@link #isEmpty()} as {@code * entrySet().isEmpty()} instead of {@code size() == 0} to speed up * implementations where {@code size()} is O(n), and it delegates the {@code * isEmpty()} methods of its key set and value collection to this * implementation. */ @GwtCompatible abstract static class ImprovedAbstractMap extends AbstractMap { /** * Creates the entry set to be returned by {@link #entrySet()}. This method * is invoked at most once on a given map, at the time when {@code entrySet} * is first called. */ protected abstract Set> createEntrySet(); private Set> entrySet; @Override public Set> entrySet() { Set> result = entrySet; if (result == null) { entrySet = result = createEntrySet(); } return result; } private Set keySet; @Override public Set keySet() { Set result = keySet; if (result == null) { return keySet = new KeySet() { @Override Map map() { return ImprovedAbstractMap.this; } }; } return result; } private Collection values; @Override public Collection values() { Collection result = values; if (result == null) { return values = new Values() { @Override Map map() { return ImprovedAbstractMap.this; } }; } return result; } } static final MapJoiner STANDARD_JOINER = Collections2.STANDARD_JOINER.withKeyValueSeparator("="); /** * Delegates to {@link Map#get}. Returns {@code null} on {@code * ClassCastException} and {@code NullPointerException}. */ static V safeGet(Map map, Object key) { checkNotNull(map); try { return map.get(key); } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } } /** * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code * ClassCastException} and {@code NullPointerException}. */ static boolean safeContainsKey(Map map, Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException e) { return false; } catch (NullPointerException e) { return false; } } /** * Delegates to {@link Map#remove}. Returns {@code null} on {@code * ClassCastException} and {@code NullPointerException}. */ static V safeRemove(Map map, Object key) { checkNotNull(map); try { return map.remove(key); } catch (ClassCastException e) { return null; } catch (NullPointerException e) { return null; } } /** * Implements {@code Collection.contains} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * *

Note that {@code c} is the backing (delegate) collection, rather than * the forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object that might be contained in {@code c} * @return {@code true} if {@code c} contains {@code o} */ static boolean containsEntryImpl(Collection> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.contains(unmodifiableEntry((Entry) o)); } /** * Implements {@code Collection.remove} safely for forwarding collections of * map entries. If {@code o} is an instance of {@code Map.Entry}, it is * wrapped using {@link #unmodifiableEntry} to protect against a possible * nefarious equals method. * *

Note that {@code c} is backing (delegate) collection, rather than the * forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object to remove from {@code c} * @return {@code true} if {@code c} was changed */ static boolean removeEntryImpl(Collection> c, Object o) { if (!(o instanceof Entry)) { return false; } return c.remove(unmodifiableEntry((Entry) o)); } /** * An implementation of {@link Map#equals}. */ static boolean equalsImpl(Map map, Object object) { if (map == object) { return true; } if (object instanceof Map) { Map o = (Map) object; return map.entrySet().equals(o.entrySet()); } return false; } /** * An implementation of {@link Map#toString}. */ static String toStringImpl(Map map) { StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{'); STANDARD_JOINER.appendTo(sb, map); return sb.append('}').toString(); } /** * An implementation of {@link Map#putAll}. */ static void putAllImpl( Map self, Map map) { for (Map.Entry entry : map.entrySet()) { self.put(entry.getKey(), entry.getValue()); } } /** * An admittedly inefficient implementation of {@link Map#containsKey}. */ static boolean containsKeyImpl(Map map, @Nullable Object key) { return Iterators.contains(keyIterator(map.entrySet().iterator()), key); } /** * An implementation of {@link Map#containsValue}. */ static boolean containsValueImpl(Map map, @Nullable Object value) { return Iterators.contains(valueIterator(map.entrySet().iterator()), value); } static Iterator keyIterator(Iterator> entryIterator) { return new TransformedIterator, K>(entryIterator) { @Override K transform(Entry entry) { return entry.getKey(); } }; } abstract static class KeySet extends Sets.ImprovedAbstractSet { abstract Map map(); @Override public Iterator iterator() { return keyIterator(map().entrySet().iterator()); } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(Object o) { return map().containsKey(o); } @Override public boolean remove(Object o) { if (contains(o)) { map().remove(o); return true; } return false; } @Override public void clear() { map().clear(); } } @Nullable static K keyOrNull(@Nullable Entry entry) { return (entry == null) ? null : entry.getKey(); } @Nullable static V valueOrNull(@Nullable Entry entry) { return (entry == null) ? null : entry.getValue(); } @GwtIncompatible("NavigableMap") static class NavigableKeySet extends KeySet implements NavigableSet { private final NavigableMap map; NavigableKeySet(NavigableMap map) { this.map = checkNotNull(map); } @Override NavigableMap map() { return map; } @Override public Comparator comparator() { return map().comparator(); } @Override public K first() { return map().firstKey(); } @Override public K last() { return map().lastKey(); } @Override public K lower(K e) { return map().lowerKey(e); } @Override public K floor(K e) { return map().floorKey(e); } @Override public K ceiling(K e) { return map().ceilingKey(e); } @Override public K higher(K e) { return map().higherKey(e); } @Override public K pollFirst() { return keyOrNull(map().pollFirstEntry()); } @Override public K pollLast() { return keyOrNull(map().pollLastEntry()); } @Override public NavigableSet descendingSet() { return map().descendingKeySet(); } @Override public Iterator descendingIterator() { return descendingSet().iterator(); } @Override public NavigableSet subSet( K fromElement, boolean fromInclusive, K toElement, boolean toInclusive) { return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); } @Override public NavigableSet headSet(K toElement, boolean inclusive) { return map().headMap(toElement, inclusive).navigableKeySet(); } @Override public NavigableSet tailSet(K fromElement, boolean inclusive) { return map().tailMap(fromElement, inclusive).navigableKeySet(); } @Override public SortedSet subSet(K fromElement, K toElement) { return subSet(fromElement, true, toElement, false); } @Override public SortedSet headSet(K toElement) { return headSet(toElement, false); } @Override public SortedSet tailSet(K fromElement) { return tailSet(fromElement, true); } } static Iterator valueIterator(Iterator> entryIterator) { return new TransformedIterator, V>(entryIterator) { @Override V transform(Entry entry) { return entry.getValue(); } }; } static UnmodifiableIterator valueIterator( final UnmodifiableIterator> entryIterator) { return new UnmodifiableIterator() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public V next() { return entryIterator.next().getValue(); } }; } abstract static class Values extends AbstractCollection { abstract Map map(); @Override public Iterator iterator() { return valueIterator(map().entrySet().iterator()); } @Override public boolean remove(Object o) { try { return super.remove(o); } catch (UnsupportedOperationException e) { for (Entry entry : map().entrySet()) { if (Objects.equal(o, entry.getValue())) { map().remove(entry.getKey()); return true; } } return false; } } @Override public boolean removeAll(Collection c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set toRemove = Sets.newHashSet(); for (Entry entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRemove.add(entry.getKey()); } } return map().keySet().removeAll(toRemove); } } @Override public boolean retainAll(Collection c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set toRetain = Sets.newHashSet(); for (Entry entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRetain.add(entry.getKey()); } } return map().keySet().retainAll(toRetain); } } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(@Nullable Object o) { return map().containsValue(o); } @Override public void clear() { map().clear(); } } abstract static class EntrySet extends Sets.ImprovedAbstractSet> { abstract Map map(); @Override public int size() { return map().size(); } @Override public void clear() { map().clear(); } @Override public boolean contains(Object o) { if (o instanceof Entry) { Entry entry = (Entry) o; Object key = entry.getKey(); V value = map().get(key); return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); } return false; } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean remove(Object o) { if (contains(o)) { Entry entry = (Entry) o; return map().keySet().remove(entry.getKey()); } return false; } @Override public boolean removeAll(Collection c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove boolean changed = true; for (Object o : c) { changed |= remove(o); } return changed; } } @Override public boolean retainAll(Collection c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove Set keys = Sets.newHashSetWithExpectedSize(c.size()); for (Object o : c) { if (contains(o)) { Entry entry = (Entry) o; keys.add(entry.getKey()); } } return map().keySet().retainAll(keys); } } } @GwtIncompatible("NavigableMap") abstract static class DescendingMap extends ForwardingMap implements NavigableMap { abstract NavigableMap forward(); @Override protected final Map delegate() { return forward(); } private transient Comparator comparator; @SuppressWarnings("unchecked") @Override public Comparator comparator() { Comparator result = comparator; if (result == null) { Comparator forwardCmp = forward().comparator(); if (forwardCmp == null) { forwardCmp = (Comparator) Ordering.natural(); } result = comparator = reverse(forwardCmp); } return result; } // If we inline this, we get a javac error. private static Ordering reverse(Comparator forward) { return Ordering.from(forward).reverse(); } @Override public K firstKey() { return forward().lastKey(); } @Override public K lastKey() { return forward().firstKey(); } @Override public Entry lowerEntry(K key) { return forward().higherEntry(key); } @Override public K lowerKey(K key) { return forward().higherKey(key); } @Override public Entry floorEntry(K key) { return forward().ceilingEntry(key); } @Override public K floorKey(K key) { return forward().ceilingKey(key); } @Override public Entry ceilingEntry(K key) { return forward().floorEntry(key); } @Override public K ceilingKey(K key) { return forward().floorKey(key); } @Override public Entry higherEntry(K key) { return forward().lowerEntry(key); } @Override public K higherKey(K key) { return forward().lowerKey(key); } @Override public Entry firstEntry() { return forward().lastEntry(); } @Override public Entry lastEntry() { return forward().firstEntry(); } @Override public Entry pollFirstEntry() { return forward().pollLastEntry(); } @Override public Entry pollLastEntry() { return forward().pollFirstEntry(); } @Override public NavigableMap descendingMap() { return forward(); } private transient Set> entrySet; @Override public Set> entrySet() { Set> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract Iterator> entryIterator(); Set> createEntrySet() { return new EntrySet() { @Override Map map() { return DescendingMap.this; } @Override public Iterator> iterator() { return entryIterator(); } }; } @Override public Set keySet() { return navigableKeySet(); } private transient NavigableSet navigableKeySet; @Override public NavigableSet navigableKeySet() { NavigableSet result = navigableKeySet; return (result == null) ? navigableKeySet = new NavigableKeySet(this) : result; } @Override public NavigableSet descendingKeySet() { return forward().navigableKeySet(); } @Override public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); } @Override public NavigableMap headMap(K toKey, boolean inclusive) { return forward().tailMap(toKey, inclusive).descendingMap(); } @Override public NavigableMap tailMap(K fromKey, boolean inclusive) { return forward().headMap(fromKey, inclusive).descendingMap(); } @Override public SortedMap subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public SortedMap headMap(K toKey) { return headMap(toKey, false); } @Override public SortedMap tailMap(K fromKey) { return tailMap(fromKey, true); } @Override public Collection values() { return new Values() { @Override Map map() { return DescendingMap.this; } }; } } }