Class Maps
Map
instances (including instances of SortedMap
, BiMap
, etc.). Also see this class's counterparts Lists
, Sets
and Queues
.
See the Guava User Guide article on Maps
.
- Since:
- 2.0
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprivate static class
private static class
private static final class
(package private) static class
private static enum
(package private) static class
static interface
A transformation of the value of a key-value pair, using both key and value as inputs.(package private) static final class
(package private) static class
private static class
private static class
private static class
private static final class
(package private) static class
(package private) static class
(package private) static class
private static final class
(package private) static class
private static class
(package private) static class
(package private) static class
(package private) static class
private static class
(package private) static class
private static class
(package private) static class
The implementation ofMultimaps.unmodifiableEntries(java.util.Collection<java.util.Map.Entry<K, V>>)
.(package private) static class
The implementation ofunmodifiableEntrySet(Set)
.(package private) static class
(package private) static class
(package private) static class
(package private) static class
AbstractMap
extension that makes it easy to cache customized keySet, values, and entrySet views. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <A,
B> Converter <A, B> asConverter
(BiMap<A, B> bimap) Returns aConverter
that converts values usingbimap.get()
, and whose inverse view converts values usingbimap.inverse()
.get()
.asEntryToEntryFunction
(Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Views an entry transformer as a function from entries to entries.asEntryToValueFunction
(Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Views an entry transformer as a function fromEntry
to values.(package private) static <K,
V1, V2>
Maps.EntryTransformer<K, V1, V2> asEntryTransformer
(Function<? super V1, V2> function) Views a function as an entry transformer that ignores the entry key.static <K,
V> NavigableMap <K, V> asMap
(NavigableSet<K> set, Function<? super K, V> function) Returns a view of the navigable set as a map, mapping keys from the set according to the specified function.static <K,
V> Map <K, V> Returns a liveMap
view whose keys are the contents ofset
and whose values are computed on demand usingfunction
.static <K,
V> SortedMap <K, V> Returns a view of the sorted set as a map, mapping keys from the set according to the specified function.asMapEntryIterator
(Set<K> set, Function<? super K, V> function) (package private) static <K,
V1, V2>
Function<V1, V2> asValueToValueFunction
(Maps.EntryTransformer<? super K, V1, V2> transformer, K key) (package private) static int
capacity
(int 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).(package private) static <K,
V> boolean containsEntryImpl
(Collection<Map.Entry<K, V>> c, Object o) ImplementsCollection.contains
safely for forwarding collections of map entries.(package private) static boolean
containsKeyImpl
(Map<?, ?> map, Object key) An admittedly inefficient implementation ofMap.containsKey(java.lang.Object)
.(package private) static boolean
containsValueImpl
(Map<?, ?> map, Object value) An implementation ofMap.containsValue(java.lang.Object)
.static <K,
V> MapDifference <K, V> difference
(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) Computes the difference between two maps.static <K,
V> MapDifference <K, V> difference
(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence) Computes the difference between two maps.static <K,
V> SortedMapDifference <K, V> difference
(SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) Computes the difference between two sorted maps, using the comparator of the left map, orOrdering.natural()
if the left map uses the natural ordering of its elements.private static <K,
V> void doDifference
(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) (package private) static boolean
equalsImpl
(Map<?, ?> map, Object object) An implementation ofMap.equals(java.lang.Object)
.static <K,
V> BiMap <K, V> filterEntries
(BiMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a bimap containing the mappings inunfiltered
that satisfy a predicate.static <K,
V> Map <K, V> filterEntries
(Map<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a map containing the mappings inunfiltered
that satisfy a predicate.static <K,
V> NavigableMap <K, V> filterEntries
(NavigableMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a sorted map containing the mappings inunfiltered
that satisfy a predicate.static <K,
V> SortedMap <K, V> filterEntries
(SortedMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a sorted map containing the mappings inunfiltered
that satisfy a predicate.private static <K,
V> Map <K, V> filterFiltered
(Maps.AbstractFilteredMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered map.private static <K,
V> BiMap <K, V> filterFiltered
(Maps.FilteredEntryBiMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered map.private static <K,
V> NavigableMap <K, V> filterFiltered
(Maps.FilteredEntryNavigableMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered navigable map.private static <K,
V> SortedMap <K, V> filterFiltered
(Maps.FilteredEntrySortedMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered sorted map.static <K,
V> BiMap <K, V> filterKeys
(BiMap<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a bimap containing the mappings inunfiltered
whose keys satisfy a predicate.static <K,
V> Map <K, V> filterKeys
(Map<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a map containing the mappings inunfiltered
whose keys satisfy a predicate.static <K,
V> NavigableMap <K, V> filterKeys
(NavigableMap<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a navigable map containing the mappings inunfiltered
whose keys satisfy a predicate.static <K,
V> SortedMap <K, V> filterKeys
(SortedMap<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a sorted map containing the mappings inunfiltered
whose keys satisfy a predicate.static <K,
V> BiMap <K, V> filterValues
(BiMap<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a bimap containing the mappings inunfiltered
whose values satisfy a predicate.static <K,
V> Map <K, V> filterValues
(Map<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a map containing the mappings inunfiltered
whose values satisfy a predicate.static <K,
V> NavigableMap <K, V> filterValues
(NavigableMap<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a navigable map containing the mappings inunfiltered
whose values satisfy a predicate.static <K,
V> SortedMap <K, V> filterValues
(SortedMap<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a sorted map containing the mappings inunfiltered
whose values satisfy a predicate.static ImmutableMap
<String, String> fromProperties
(Properties properties) Creates anImmutableMap<String, String>
from aProperties
instance.static <K,
V> Map.Entry <K, V> immutableEntry
(K key, V value) Returns an immutable map entry with the specified key and value.static <K extends Enum<K>,
V>
ImmutableMap<K, V> immutableEnumMap
(Map<K, ? extends V> map) Returns an immutable map instance containing the given entries.(package private) static <E> ImmutableMap
<E, Integer> indexMap
(Collection<E> list) Returns a map from the ith element of list to i.(package private) static <K,
V> Iterator <K> keyIterator
(Iterator<Map.Entry<K, V>> entryIterator) (package private) static <K> K
keyPredicateOnEntries
(Predicate<? super K> keyPredicate) static <K,
V> ConcurrentMap <K, V> Creates a new emptyConcurrentHashMap
instance.newEnumMap
(Class<K> type) Creates anEnumMap
instance.newEnumMap
(Map<K, ? extends V> map) Creates anEnumMap
with the same mappings as the specified map.static <K,
V> HashMap <K, V> Creates a mutable, emptyHashMap
instance.static <K,
V> HashMap <K, V> newHashMap
(Map<? extends K, ? extends V> map) Creates a mutableHashMap
instance with the same mappings as the specified map.static <K,
V> HashMap <K, V> newHashMapWithExpectedSize
(int expectedSize) Creates aHashMap
instance, with a high enough "initial capacity" that it should holdexpectedSize
elements without growth.static <K,
V> IdentityHashMap <K, V> Creates anIdentityHashMap
instance.static <K,
V> LinkedHashMap <K, V> Creates a mutable, empty, insertion-orderedLinkedHashMap
instance.static <K,
V> LinkedHashMap <K, V> newLinkedHashMap
(Map<? extends K, ? extends V> map) Creates a mutable, insertion-orderedLinkedHashMap
instance with the same mappings as the specified map.static <K,
V> LinkedHashMap <K, V> newLinkedHashMapWithExpectedSize
(int expectedSize) Creates aLinkedHashMap
instance, with a high enough "initial capacity" that it should holdexpectedSize
elements without growth.static <K extends Comparable,
V>
TreeMap<K, V> Creates a mutable, emptyTreeMap
instance using the natural ordering of its elements.static <C,
K extends C, V>
TreeMap<K, V> newTreeMap
(Comparator<C> comparator) Creates a mutable, emptyTreeMap
instance using the given comparator.static <K,
V> TreeMap <K, V> newTreeMap
(SortedMap<K, ? extends V> map) Creates a mutableTreeMap
instance with the same mappings as the specified map and using the same ordering as the specified map.(package private) static <E> Comparator
<? super E> orNaturalOrder
(Comparator<? super E> comparator) Returns the specified comparator if not null; otherwise returnsOrdering.natural()
.(package private) static <K,
V> void putAllImpl
(Map<K, V> self, Map<? extends K, ? extends V> map) An implementation ofMap.putAll(java.util.Map<? extends K, ? extends V>)
.(package private) static <K,
V> boolean removeEntryImpl
(Collection<Map.Entry<K, V>> c, Object o) ImplementsCollection.remove
safely for forwarding collections of map entries.private static <E> NavigableSet
<E> removeOnlyNavigableSet
(NavigableSet<E> set) private static <E> Set
<E> removeOnlySet
(Set<E> set) private static <E> SortedSet
<E> removeOnlySortedSet
(SortedSet<E> set) (package private) static boolean
safeContainsKey
(Map<?, ?> map, Object key) Delegates toMap.containsKey(java.lang.Object)
.(package private) static <V> V
Delegates toMap.get(java.lang.Object)
.(package private) static <V> V
safeRemove
(Map<?, V> map, Object key) Delegates toMap.remove(java.lang.Object)
.static <K extends Comparable<? super K>,
V>
NavigableMap<K, V> subMap
(NavigableMap<K, V> map, Range<K> range) Returns a view of the portion ofmap
whose keys are contained byrange
.static <K,
V> BiMap <K, V> synchronizedBiMap
(BiMap<K, V> bimap) Returns a synchronized (thread-safe) bimap backed by the specified bimap.static <K,
V> NavigableMap <K, V> synchronizedNavigableMap
(NavigableMap<K, V> navigableMap) Returns a synchronized (thread-safe) navigable map backed by the specified navigable map.static <T,
K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap
(Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction) Returns aCollector
that accumulates elements into anImmutableMap
whose keys and values are the result of applying the provided mapping functions to the input elements.static <T,
K extends Enum<K>, V>
Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap
(Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) Returns aCollector
that accumulates elements into anImmutableMap
whose keys and values are the result of applying the provided mapping functions to the input elements.static <K,
V> ImmutableMap <K, V> Returns an immutable map whose keys are the distinct elements ofkeys
and whose value for each key was computed byvalueFunction
.static <K,
V> ImmutableMap <K, V> Returns an immutable map whose keys are the distinct elements ofkeys
and whose value for each key was computed byvalueFunction
.(package private) static String
toStringImpl
(Map<?, ?> map) An implementation ofinvalid reference
Map#toString
static <K,
V1, V2>
Map<K, V2> transformEntries
(Map<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Returns a view of a map whose values are derived from the original map's entries.static <K,
V1, V2>
NavigableMap<K, V2> transformEntries
(NavigableMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Returns a view of a navigable map whose values are derived from the original navigable map's entries.static <K,
V1, V2>
SortedMap<K, V2> transformEntries
(SortedMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Returns a view of a sorted map whose values are derived from the original sorted map's entries.(package private) static <V2,
K, V1>
Map.Entry<K, V2> transformEntry
(Maps.EntryTransformer<? super K, ? super V1, V2> transformer, Map.Entry<K, V1> entry) Returns a view of an entry transformed by the specified transformer.static <K,
V1, V2>
Map<K, V2> transformValues
(Map<K, V1> fromMap, Function<? super V1, V2> function) Returns a view of a map where each value is transformed by a function.static <K,
V1, V2>
NavigableMap<K, V2> transformValues
(NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) Returns a view of a navigable map where each value is transformed by a function.static <K,
V1, V2>
SortedMap<K, V2> transformValues
(SortedMap<K, V1> fromMap, Function<? super V1, V2> function) Returns a view of a sorted map where each value is transformed by a function.static <K,
V> ImmutableMap <K, V> uniqueIndex
(Iterable<V> values, Function<? super V, K> keyFunction) Returns a map with the givenvalues
, indexed by keys derived from those values.static <K,
V> ImmutableMap <K, V> uniqueIndex
(Iterator<V> values, Function<? super V, K> keyFunction) Returns a map with the givenvalues
, indexed by keys derived from those values.private static <K,
V> ImmutableMap <K, V> uniqueIndex
(Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) static <K,
V> BiMap <K, V> unmodifiableBiMap
(BiMap<? extends K, ? extends V> bimap) Returns an unmodifiable view of the specified bimap.(package private) static <K,
V> Map.Entry <K, V> unmodifiableEntry
(Map.Entry<? extends K, ? extends V> entry) Returns an unmodifiable view of the specified map entry.(package private) static <K,
V> UnmodifiableIterator <Map.Entry<K, V>> unmodifiableEntryIterator
(Iterator<Map.Entry<K, V>> entryIterator) unmodifiableEntrySet
(Set<Map.Entry<K, V>> entrySet) Returns an unmodifiable view of the specified set of entries.private static <K,
V> Map <K, V> unmodifiableMap
(Map<K, ? extends V> map) static <K,
V> NavigableMap <K, V> unmodifiableNavigableMap
(NavigableMap<K, ? extends V> map) Returns an unmodifiable view of the specified navigable map.private static <K,
V> Map.Entry <K, V> unmodifiableOrNull
(Map.Entry<K, ? extends V> entry) (package private) static <K,
V> Iterator <V> valueIterator
(Iterator<Map.Entry<K, V>> entryIterator) (package private) static <V> V
valueOrNull
(Map.Entry<?, V> entry) valuePredicateOnEntries
(Predicate<? super V> valuePredicate)
-
Constructor Details
-
Maps
private Maps()
-
-
Method Details
-
keyFunction
-
valueFunction
-
keyIterator
-
valueIterator
-
immutableEnumMap
Returns an immutable map instance containing the given entries. Internally, the returned map will be backed by anEnumMap
.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.
- Parameters:
map
- the map to make an immutable copy of- Returns:
- an immutable map containing those entries
- Since:
- 14.0
-
toImmutableEnumMap
public static <T,K extends Enum<K>, Collector<T,V> ?, toImmutableEnumMapImmutableMap<K, V>> (Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction) Returns aCollector
that accumulates elements into anImmutableMap
whose keys and values are the result of applying the provided mapping functions to the input elements. The resulting implementation is specialized for enum key types. The returned map and its views will iterate over keys in their enum definition order, not encounter order.If the mapped keys contain duplicates, an
IllegalArgumentException
is thrown when the collection operation is performed. (This differs from theCollector
returned byCollectors.toMap(Function, Function)
, which throws anIllegalStateException
.)- Since:
- 21.0
-
toImmutableEnumMap
public static <T,K extends Enum<K>, Collector<T,V> ?, toImmutableEnumMapImmutableMap<K, V>> (Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) Returns aCollector
that accumulates elements into anImmutableMap
whose keys and values are the result of applying the provided mapping functions to the input elements. The resulting implementation is specialized for enum key types. The returned map and its views will iterate over keys in their enum definition order, not encounter order.If the mapped keys contain duplicates, the values are merged using the specified merging function.
- Since:
- 21.0
-
newHashMap
Creates a mutable, emptyHashMap
instance.Note: if mutability is not required, use
ImmutableMap.of()
instead.Note: if
K
is anenum
type, usenewEnumMap(java.lang.Class<K>)
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
HashMap
constructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
HashMap
-
newHashMap
Creates a mutableHashMap
instance with the same mappings as the specified map.Note: if mutability is not required, use
ImmutableMap.copyOf(Map)
instead.Note: if
K
is anEnum
type, usenewEnumMap(java.lang.Class<K>)
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
HashMap
constructor directly, taking advantage of "diamond" syntax.- Parameters:
map
- the mappings to be placed in the new map- Returns:
- a new
HashMap
initialized with the mappings frommap
-
newHashMapWithExpectedSize
Creates aHashMap
instance, with a high enough "initial capacity" that it should holdexpectedSize
elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.- Parameters:
expectedSize
- the number of entries you expect to add to the returned map- Returns:
- a new, empty
HashMap
with enough capacity to holdexpectedSize
entries without resizing - Throws:
IllegalArgumentException
- ifexpectedSize
is negative
-
capacity
static int capacity(int 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). -
newLinkedHashMap
Creates a mutable, empty, insertion-orderedLinkedHashMap
instance.Note: if mutability is not required, use
ImmutableMap.of()
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
LinkedHashMap
constructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
LinkedHashMap
-
newLinkedHashMap
Creates a mutable, insertion-orderedLinkedHashMap
instance with the same mappings as the specified map.Note: if mutability is not required, use
ImmutableMap.copyOf(Map)
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
LinkedHashMap
constructor directly, taking advantage of "diamond" syntax.- Parameters:
map
- the mappings to be placed in the new map- Returns:
- a new,
LinkedHashMap
initialized with the mappings frommap
-
newLinkedHashMapWithExpectedSize
Creates aLinkedHashMap
instance, with a high enough "initial capacity" that it should holdexpectedSize
elements without growth. This behavior cannot be broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method isn't inadvertently oversizing the returned map.- Parameters:
expectedSize
- the number of entries you expect to add to the returned map- Returns:
- a new, empty
LinkedHashMap
with enough capacity to holdexpectedSize
entries without resizing - Throws:
IllegalArgumentException
- ifexpectedSize
is negative- Since:
- 19.0
-
newConcurrentMap
Creates a new emptyConcurrentHashMap
instance.- Since:
- 3.0
-
newTreeMap
Creates a mutable, emptyTreeMap
instance using the natural ordering of its elements.Note: if mutability is not required, use
ImmutableSortedMap.of()
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeMap
constructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
TreeMap
-
newTreeMap
Creates a mutableTreeMap
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
ImmutableSortedMap.copyOfSorted(SortedMap)
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeMap
constructor directly, taking advantage of "diamond" syntax.- Parameters:
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- Returns:
- a new
TreeMap
initialized with the mappings frommap
and using the comparator ofmap
-
newTreeMap
Creates a mutable, emptyTreeMap
instance using the given comparator.Note: if mutability is not required, use
ImmutableSortedMap.orderedBy(comparator).build()
instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
TreeMap
constructor directly, taking advantage of "diamond" syntax.- Parameters:
comparator
- the comparator to sort the keys with- Returns:
- a new, empty
TreeMap
-
newEnumMap
Creates anEnumMap
instance.- Parameters:
type
- the key type for this map- Returns:
- a new, empty
EnumMap
-
newEnumMap
Creates anEnumMap
with the same mappings as the specified map.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
EnumMap
constructor directly, taking advantage of "diamond" syntax.- Parameters:
map
- the map from which to initialize thisEnumMap
- Returns:
- a new
EnumMap
initialized with the mappings frommap
- Throws:
IllegalArgumentException
- ifm
is not anEnumMap
instance and contains no mappings
-
newIdentityHashMap
Creates anIdentityHashMap
instance.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
IdentityHashMap
constructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
IdentityHashMap
-
difference
public static <K,V> MapDifference<K,V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) 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
HashMap
instances internally, the keys of the supplied maps must be well-behaved with respect toObject.equals(java.lang.Object)
andObject.hashCode()
.Note:If you only need to know whether two maps have the same mappings, call
left.equals(right)
instead of this method.- Parameters:
left
- the map to treat as the "left" map for purposes of comparisonright
- the map to treat as the "right" map for purposes of comparison- Returns:
- the difference between the two maps
-
difference
public static <K,V> MapDifference<K,V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence) 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
HashMap
instances internally, the keys of the supplied maps must be well-behaved with respect toObject.equals(java.lang.Object)
andObject.hashCode()
.- Parameters:
left
- the map to treat as the "left" map for purposes of comparisonright
- the map to treat as the "right" map for purposes of comparisonvalueEquivalence
- the equivalence relationship to use to compare values- Returns:
- the difference between the two maps
- Since:
- 10.0
-
difference
public static <K,V> SortedMapDifference<K,V> difference(SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) Computes the difference between two sorted maps, using the comparator of the left map, orOrdering.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
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
left.equals(right)
instead of this method.- Parameters:
left
- the map to treat as the "left" map for purposes of comparisonright
- the map to treat as the "right" map for purposes of comparison- Returns:
- the difference between the two maps
- Since:
- 11.0
-
doDifference
private static <K,V> void doDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) -
unmodifiableMap
-
orNaturalOrder
Returns the specified comparator if not null; otherwise returnsOrdering.natural()
. This method is an abomination of generics; the only purpose of this method is to contain the ugly type-casting in one place. -
asMap
Returns a liveMap
view whose keys are the contents ofset
and whose values are computed on demand usingfunction
. To get an immutable copy instead, usetoMap(Iterable, Function)
.Specifically, for each
k
in the backing set, the returned map has an entry mappingk
tofunction.apply(k)
. ThekeySet
,values
, andentrySet
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
null
, caution is required to make sure the set does not containnull
, because the view cannot stopnull
from being added to the set.Warning: This method assumes that for any instance
k
of key typeK
,k.equals(k2)
implies thatk2
is also of typeK
. Using a key type for which this may not hold, such asArrayList
, may risk aClassCastException
when calling methods on the resulting map view.- Since:
- 14.0
-
asMap
Returns a view of the sorted set as a map, mapping keys from the set according to the specified function.Specifically, for each
k
in the backing set, the returned map has an entry mappingk
tofunction.apply(k)
. ThekeySet
,values
, andentrySet
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
null
, caution is required to make sure the set does not containnull
, because the view cannot stopnull
from being added to the set.Warning: This method assumes that for any instance
k
of key typeK
,k.equals(k2)
implies thatk2
is also of typeK
. Using a key type for which this may not hold, such asArrayList
, may risk aClassCastException
when calling methods on the resulting map view.- Since:
- 14.0
-
asMapEntryIterator
-
removeOnlySet
-
removeOnlySortedSet
-
toMap
Returns an immutable map whose keys are the distinct elements ofkeys
and whose value for each key was computed byvalueFunction
. The map's iteration order is the order of the first appearance of each key inkeys
.When there are multiple instances of a key in
keys
, it is unspecified whethervalueFunction
will be applied to more than one instance of that key and, if it is, which result will be mapped to that key in the returned map.If
keys
is aSet
, a live view can be obtained instead of a copy usingasMap(Set, Function)
.Note: on Java 8+, it is usually better to use streams. For example:
import static com.google.common.collect.ImmutableMap.toImmutableMap; ... ImmutableMap<Color, String> colorNames = allColors.stream().collect(toImmutableMap(c -> c, c -> c.toString()));
Streams provide a more standard and flexible API and the lambdas make it clear what the keys and values in the map are.
- Throws:
NullPointerException
- if any element ofkeys
isnull
, or ifvalueFunction
producesnull
for any key- Since:
- 14.0
-
toMap
Returns an immutable map whose keys are the distinct elements ofkeys
and whose value for each key was computed byvalueFunction
. The map's iteration order is the order of the first appearance of each key inkeys
.When there are multiple instances of a key in
keys
, it is unspecified whethervalueFunction
will be applied to more than one instance of that key and, if it is, which result will be mapped to that key in the returned map.- Throws:
NullPointerException
- if any element ofkeys
isnull
, or ifvalueFunction
producesnull
for any key- Since:
- 14.0
-
uniqueIndex
public static <K,V> ImmutableMap<K,V> uniqueIndex(Iterable<V> values, Function<? super V, K> keyFunction) Returns a map with the givenvalues
, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applyingkeyFunction
to that value. These entries appear in the same order as the input values. Example usage:Color red = new Color("red", 255, 0, 0); ... ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue); ImmutableMap<String, Color> colorForName = uniqueIndex(allColors, c -> c.toString()); assertThat(colorForName).containsEntry("red", red);
If your index may associate multiple values with each key, use
Multimaps.index
.Note: on Java 8+, it is usually better to use streams. For example:
import static com.google.common.collect.ImmutableMap.toImmutableMap; ... ImmutableMap<String, Color> colorForName = allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c));
Streams provide a more standard and flexible API and the lambdas make it clear what the keys and values in the map are.
- Parameters:
values
- the values to use when constructing theMap
keyFunction
- the function used to produce the key for each value- Returns:
- a map mapping the result of evaluating the function
keyFunction
on each value in the input collection to that value - Throws:
IllegalArgumentException
- ifkeyFunction
produces the same key for more than one value in the input collectionNullPointerException
- if any element ofvalues
isnull
, or ifkeyFunction
producesnull
for any value
-
uniqueIndex
public static <K,V> ImmutableMap<K,V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) Returns a map with the givenvalues
, indexed by keys derived from those values. In other words, each input value produces an entry in the map whose key is the result of applyingkeyFunction
to that value. These entries appear in the same order as the input values. Example usage:Color red = new Color("red", 255, 0, 0); ... Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator(); Map<String, Color> colorForName = uniqueIndex(allColors, toStringFunction()); assertThat(colorForName).containsEntry("red", red);
If your index may associate multiple values with each key, use
Multimaps.index
.- Parameters:
values
- the values to use when constructing theMap
keyFunction
- the function used to produce the key for each value- Returns:
- a map mapping the result of evaluating the function
keyFunction
on each value in the input collection to that value - Throws:
IllegalArgumentException
- ifkeyFunction
produces the same key for more than one value in the input collectionNullPointerException
- if any element ofvalues
isnull
, or ifkeyFunction
producesnull
for any value- Since:
- 10.0
-
uniqueIndex
private static <K,V> ImmutableMap<K,V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) -
fromProperties
Creates anImmutableMap<String, String>
from aProperties
instance. Properties normally derive fromMap<Object, Object>
, but they typically contain strings, which is awkward. This method lets you get a plain-old-Map
out of aProperties
.- Parameters:
properties
- aProperties
object to be converted- Returns:
- an immutable map containing all the entries in
properties
- Throws:
ClassCastException
- if any key inproperties
is not aString
NullPointerException
- if any key or value inproperties
is null
-
immutableEntry
Returns an immutable map entry with the specified key and value. TheMap.Entry.setValue(V)
operation throws anUnsupportedOperationException
.The returned entry is serializable.
Java 9 users: consider using
java.util.Map.entry(key, value)
if the key and value are non-null and the entry does not need to be serializable.- Parameters:
key
- the key to be associated with the returned entryvalue
- the value to be associated with the returned entry
-
unmodifiableEntrySet
Returns an unmodifiable view of the specified set of entries. TheMap.Entry.setValue(V)
operation throws anUnsupportedOperationException
, as do any operations that would modify the returned set.- Parameters:
entrySet
- the entries for which to return an unmodifiable view- Returns:
- an unmodifiable view of the entries
-
unmodifiableEntry
Returns an unmodifiable view of the specified map entry. TheMap.Entry.setValue(V)
operation throws anUnsupportedOperationException
. This also has the side effect of redefiningequals
to comply with the Entry contract, to avoid a possible nefarious implementation of equals.- Parameters:
entry
- the entry for which to return an unmodifiable view- Returns:
- an unmodifiable view of the entry
-
unmodifiableEntryIterator
static <K,V> UnmodifiableIterator<Map.Entry<K,V>> unmodifiableEntryIterator(Iterator<Map.Entry<K, V>> entryIterator) -
asConverter
Returns aConverter
that converts values usingbimap.get()
, and whose inverse view converts values usingbimap.inverse()
.get()
.To use a plain
Map
as aFunction
, seeFunctions.forMap(Map)
orFunctions.forMap(Map, Object)
.- Since:
- 16.0
-
synchronizedBiMap
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:
BiMap<Long, String> map = Maps.synchronizedBiMap( HashBiMap.<Long, String>create()); ... Set<Long> set = map.keySet(); // Needn't be in synchronized block ... synchronized (map) { // Synchronizing on map, not set! Iterator<Long> 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.
- Parameters:
bimap
- the bimap to be wrapped in a synchronized view- Returns:
- a synchronized view of the specified bimap
-
unmodifiableBiMap
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 anUnsupportedOperationException
.The returned bimap will be serializable if the specified bimap is serializable.
- Parameters:
bimap
- the bimap for which an unmodifiable view is to be returned- Returns:
- an unmodifiable view of the specified bimap
-
transformValues
public static <K,V1, Map<K,V2> V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) 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:
... printsMap<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); Function<Integer, Double> sqrt = new Function<Integer, Double>() { public Double apply(Integer in) { return Math.sqrt((int) in); } }; Map<String, Double> transformed = Maps.transformValues(map, sqrt); System.out.println(transformed);
{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
Map.containsValue(java.lang.Object)
andMap.toString()
. For this to perform well,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. -
transformValues
public static <K,V1, SortedMap<K,V2> V2> transformValues(SortedMap<K, V1> fromMap, Function<? super V1, V2> 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:
... printsSortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); Function<Integer, Double> sqrt = new Function<Integer, Double>() { public Double apply(Integer in) { return Math.sqrt((int) in); } }; SortedMap<String, Double> transformed = Maps.transformValues(map, sqrt); System.out.println(transformed);
{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
Map.containsValue(java.lang.Object)
andMap.toString()
. For this to perform well,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
-
transformEntries
public static <K,V1, Map<K,V2> V2> transformEntries(Map<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Returns a view of a map whose values are derived from the original map's entries. In contrast totransformValues(java.util.Map<K, V1>, com.google.common.base.Function<? super V1, V2>)
, 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:
... printsMap<String, Boolean> options = ImmutableMap.of("verbose", true, "sort", false); EntryTransformer<String, Boolean, String> flagPrefixer = new EntryTransformer<String, Boolean, String>() { public String transformEntry(String key, Boolean value) { return value ? key : "no" + key; } }; Map<String, String> transformed = Maps.transformEntries(options, flagPrefixer); System.out.println(transformed);
{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
Map.containsValue(java.lang.Object)
andObject.toString()
. For this to perform well,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
k
ofEntryTransformer
key typeK
,k.equals(k2)
implies thatk2
is also of typeK
. Using anEntryTransformer
key type for which this may not hold, such asArrayList
, may risk aClassCastException
when calling methods on the transformed map.- Since:
- 7.0
-
transformEntries
public static <K,V1, SortedMap<K,V2> V2> transformEntries(SortedMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Returns a view of a sorted map whose values are derived from the original sorted map's entries. In contrast totransformValues(java.util.Map<K, V1>, com.google.common.base.Function<? super V1, V2>)
, 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:
... printsMap<String, Boolean> options = ImmutableSortedMap.of("verbose", true, "sort", false); EntryTransformer<String, Boolean, String> flagPrefixer = new EntryTransformer<String, Boolean, String>() { public String transformEntry(String key, Boolean value) { return value ? key : "yes" + key; } }; SortedMap<String, String> transformed = Maps.transformEntries(options, flagPrefixer); System.out.println(transformed);
{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
Map.containsValue(java.lang.Object)
andObject.toString()
. For this to perform well,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
k
ofEntryTransformer
key typeK
,k.equals(k2)
implies thatk2
is also of typeK
. Using anEntryTransformer
key type for which this may not hold, such asArrayList
, may risk aClassCastException
when calling methods on the transformed map.- Since:
- 11.0
-
asEntryTransformer
static <K,V1, Maps.EntryTransformer<K,V2> V1, asEntryTransformerV2> (Function<? super V1, V2> function) Views a function as an entry transformer that ignores the entry key. -
asValueToValueFunction
static <K,V1, Function<V1,V2> V2> asValueToValueFunction(Maps.EntryTransformer<? super K, V1, V2> transformer, K key) -
asEntryToValueFunction
static <K,V1, Function<Map.Entry<K,V2> V1>, asEntryToValueFunctionV2> (Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Views an entry transformer as a function fromEntry
to values. -
transformEntry
static <V2,K, Map.Entry<K,V1> V2> transformEntry(Maps.EntryTransformer<? super K, ? super V1, V2> transformer, Map.Entry<K, V1> entry) Returns a view of an entry transformed by the specified transformer. -
asEntryToEntryFunction
static <K,V1, Function<Map.Entry<K,V2> V1>, asEntryToEntryFunctionMap.Entry<K, V2>> (Maps.EntryTransformer<? super K, ? super V1, V2> transformer) Views an entry transformer as a function from entries to entries. -
keyPredicateOnEntries
-
valuePredicateOnEntries
-
filterKeys
Returns a map containing the mappings inunfiltered
whose keys satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the map and its views. When given a key that doesn't satisfy the predicate, the map'sput()
andputAll()
methods throw anIllegalArgumentException
.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
keyPredicate
must be consistent with equals, as documented atPredicate.apply(T)
. Do not provide a predicate such asPredicates.instanceOf(ArrayList.class)
, which is inconsistent with equals. -
filterKeys
public static <K,V> SortedMap<K,V> filterKeys(SortedMap<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a sorted map containing the mappings inunfiltered
whose keys satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the map and its views. When given a key that doesn't satisfy the predicate, the map'sput()
andputAll()
methods throw anIllegalArgumentException
.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
keyPredicate
must be consistent with equals, as documented atPredicate.apply(T)
. Do not provide a predicate such asPredicates.instanceOf(ArrayList.class)
, which is inconsistent with equals.- Since:
- 11.0
-
filterKeys
public static <K,V> BiMap<K,V> filterKeys(BiMap<K, V> unfiltered, Predicate<? super K> keyPredicate) Returns a bimap containing the mappings inunfiltered
whose keys satisfy a predicate. The returned bimap is a live view ofunfiltered
; changes to one affect the other.The resulting bimap's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the bimap and its views. When given a key that doesn't satisfy the predicate, the bimap'sput()
,forcePut()
andputAll()
methods throw anIllegalArgumentException
.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered bimap's methods, such as
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:
entryPredicate
must be consistent with equals , as documented atPredicate.apply(T)
.- Since:
- 14.0
-
filterValues
public static <K,V> Map<K,V> filterValues(Map<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a map containing the mappings inunfiltered
whose values satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the map and its views. When given a value that doesn't satisfy the predicate, the map'sput()
,putAll()
, andMap.Entry.setValue(V)
methods throw anIllegalArgumentException
.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
valuePredicate
must be consistent with equals, as documented atPredicate.apply(T)
. Do not provide a predicate such asPredicates.instanceOf(ArrayList.class)
, which is inconsistent with equals. -
filterValues
public static <K,V> SortedMap<K,V> filterValues(SortedMap<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a sorted map containing the mappings inunfiltered
whose values satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the map and its views. When given a value that doesn't satisfy the predicate, the map'sput()
,putAll()
, andMap.Entry.setValue(V)
methods throw anIllegalArgumentException
.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
valuePredicate
must be consistent with equals, as documented atPredicate.apply(T)
. Do not provide a predicate such asPredicates.instanceOf(ArrayList.class)
, which is inconsistent with equals.- Since:
- 11.0
-
filterValues
public static <K,V> BiMap<K,V> filterValues(BiMap<K, V> unfiltered, Predicate<? super V> valuePredicate) Returns a bimap containing the mappings inunfiltered
whose values satisfy a predicate. The returned bimap is a live view ofunfiltered
; changes to one affect the other.The resulting bimap's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, but all other methods are supported by the bimap and its views. When given a value that doesn't satisfy the predicate, the bimap'sput()
,forcePut()
andputAll()
methods throw anIllegalArgumentException
. Similarly, the map's entries have aMap.Entry.setValue(V)
method that throws anIllegalArgumentException
when the provided value doesn't satisfy the predicate.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered bimap's methods, such as
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:
entryPredicate
must be consistent with equals , as documented atPredicate.apply(T)
.- Since:
- 14.0
-
filterEntries
public static <K,V> Map<K,V> filterEntries(Map<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a map containing the mappings inunfiltered
that satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, 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'sput()
andputAll()
methods throw anIllegalArgumentException
. Similarly, the map's entries have aMap.Entry.setValue(V)
method that throws anIllegalArgumentException
when the existing key and the provided value don't satisfy the predicate.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
entryPredicate
must be consistent with equals, as documented atPredicate.apply(T)
. -
filterEntries
public static <K,V> SortedMap<K,V> filterEntries(SortedMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a sorted map containing the mappings inunfiltered
that satisfy a predicate. The returned map is a live view ofunfiltered
; changes to one affect the other.The resulting map's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, 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'sput()
andputAll()
methods throw anIllegalArgumentException
. Similarly, the map's entries have aMap.Entry.setValue(V)
method that throws anIllegalArgumentException
when the existing key and the provided value don't satisfy the predicate.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered map's methods, such as
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:
entryPredicate
must be consistent with equals, as documented atPredicate.apply(T)
.- Since:
- 11.0
-
filterEntries
public static <K,V> BiMap<K,V> filterEntries(BiMap<K, V> unfiltered, Predicate<? super Map.Entry<K, V>> entryPredicate) Returns a bimap containing the mappings inunfiltered
that satisfy a predicate. The returned bimap is a live view ofunfiltered
; changes to one affect the other.The resulting bimap's
keySet()
,entrySet()
, andvalues()
views have iterators that don't supportremove()
, 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'sput()
,forcePut()
andputAll()
methods throw anIllegalArgumentException
. Similarly, the map's entries have anMap.Entry.setValue(V)
method that throws anIllegalArgumentException
when the existing key and the provided value don't satisfy the predicate.When methods such as
removeAll()
andclear()
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
unfiltered
is.Many of the filtered bimap's methods, such as
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:
entryPredicate
must be consistent with equals , as documented atPredicate.apply(T)
.- Since:
- 14.0
-
filterFiltered
private static <K,V> Map<K,V> filterFiltered(Maps.AbstractFilteredMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered map. -
filterFiltered
private static <K,V> SortedMap<K,V> filterFiltered(Maps.FilteredEntrySortedMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered sorted map. -
filterFiltered
private static <K,V> BiMap<K,V> filterFiltered(Maps.FilteredEntryBiMap<K, V> map, Predicate<? super Map.Entry<K, V>> entryPredicate) Supportclear()
,removeAll()
, andretainAll()
when filtering a filtered map. -
unmodifiableOrNull
-
safeGet
Delegates toMap.get(java.lang.Object)
. Returnsnull
onClassCastException
andNullPointerException
. -
safeContainsKey
Delegates toMap.containsKey(java.lang.Object)
. Returnsfalse
onClassCastException
andNullPointerException
. -
safeRemove
Delegates toMap.remove(java.lang.Object)
. Returnsnull
onClassCastException
andNullPointerException
. -
containsKeyImpl
An admittedly inefficient implementation ofMap.containsKey(java.lang.Object)
. -
containsValueImpl
An implementation ofMap.containsValue(java.lang.Object)
. -
containsEntryImpl
ImplementsCollection.contains
safely for forwarding collections of map entries. Ifo
is an instance ofEntry
, it is wrapped usingunmodifiableEntry(java.util.Map.Entry<? extends K, ? extends V>)
to protect against a possible nefarious equals method.Note that
c
is the backing (delegate) collection, rather than the forwarding collection.- Parameters:
c
- the delegate (unwrapped) collection of map entrieso
- the object that might be contained inc
- Returns:
true
ifc
containso
-
removeEntryImpl
ImplementsCollection.remove
safely for forwarding collections of map entries. Ifo
is an instance ofEntry
, it is wrapped usingunmodifiableEntry(java.util.Map.Entry<? extends K, ? extends V>)
to protect against a possible nefarious equals method.Note that
c
is backing (delegate) collection, rather than the forwarding collection.- Parameters:
c
- the delegate (unwrapped) collection of map entrieso
- the object to remove fromc
- Returns:
true
ifc
was changed
-
equalsImpl
An implementation ofMap.equals(java.lang.Object)
. -
toStringImpl
An implementation ofinvalid reference
Map#toString
-
putAllImpl
An implementation ofMap.putAll(java.util.Map<? extends K, ? extends V>)
. -
keyOrNull
-
valueOrNull
-
indexMap
Returns a map from the ith element of list to i.
-