Class Maps
-
Nested Class Summary
Nested Classes -
Method Summary
Modifier and TypeMethodDescriptionReturns aConverterthat converts values usingbimap.get(), and whose inverse view converts values usingbimap.inverse().get().static@Nullable Object, V extends @Nullable Object>
NavigableMapV> asMap(NavigableSet 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.Returns a liveMapview whose keys are the contents ofsetand whose values are computed on demand usingfunction.Returns a view of the sorted set as a map, mapping keys from the set according to the specified function.static@Nullable Object, V extends @Nullable Object>
MapDifferenceV> difference(Map extends K, ? extends V> left, Map extends K, ? extends V> right) Computes the difference between two maps.static@Nullable Object, V extends @Nullable Object>
MapDifferenceV> difference(Map extends K, ? extends V> left, Map extends K, ? extends V> right, Equivalence super @NonNull V> valueEquivalence) Computes the difference between two maps.static@Nullable Object, V extends @Nullable Object>
SortedMapDifferenceV> difference(SortedMap 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.filterEntries(BiMap V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a bimap containing the mappings inunfilteredthat satisfy a predicate.filterEntries(Map V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a map containing the mappings inunfilteredthat satisfy a predicate.static@Nullable Object, V extends @Nullable Object>
NavigableMapV> filterEntries(NavigableMap V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a sorted map containing the mappings inunfilteredthat satisfy a predicate.filterEntries(SortedMap V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a sorted map containing the mappings inunfilteredthat satisfy a predicate.filterKeys(BiMap V> unfiltered, Predicate super K> keyPredicate) Returns a bimap containing the mappings inunfilteredwhose keys satisfy a predicate.filterKeys(Map V> unfiltered, Predicate super K> keyPredicate) Returns a map containing the mappings inunfilteredwhose keys satisfy a predicate.static@Nullable Object, V extends @Nullable Object>
NavigableMapV> filterKeys(NavigableMap V> unfiltered, Predicate super K> keyPredicate) Returns a navigable map containing the mappings inunfilteredwhose keys satisfy a predicate.filterKeys(SortedMap V> unfiltered, Predicate super K> keyPredicate) Returns a sorted map containing the mappings inunfilteredwhose keys satisfy a predicate.filterValues(BiMap V> unfiltered, Predicate super V> valuePredicate) Returns a bimap containing the mappings inunfilteredwhose values satisfy a predicate.filterValues(Map V> unfiltered, Predicate super V> valuePredicate) Returns a map containing the mappings inunfilteredwhose values satisfy a predicate.static@Nullable Object, V extends @Nullable Object>
NavigableMapV> filterValues(NavigableMap V> unfiltered, Predicate super V> valuePredicate) Returns a navigable map containing the mappings inunfilteredwhose values satisfy a predicate.filterValues(SortedMap V> unfiltered, Predicate super V> valuePredicate) Returns a sorted map containing the mappings inunfilteredwhose values satisfy a predicate.static ImmutableMap<String, String> fromProperties(Properties properties) Creates anImmutableMapfrom aPropertiesinstance.immutableEntry(K key, V value) Returns an immutable map entry with the specified key and value.staticEnum , V>
ImmutableMapV> immutableEnumMap(Map map) Returns an immutable map instance containing the given entries.staticV> ConcurrentMap V> Creates a new emptyConcurrentHashMapinstance.newEnumMap(Class type) Creates anEnumMapinstance.newEnumMap(Map map) Creates anEnumMapwith the same mappings as the specified map.Creates a mutable, emptyHashMapinstance.newHashMap(Map extends K, ? extends V> map) Creates a mutableHashMapinstance with the same mappings as the specified map.newHashMapWithExpectedSize(int expectedSize) Creates aHashMapinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements without growth.static@Nullable Object, V extends @Nullable Object>
IdentityHashMapV> Creates anIdentityHashMapinstance.static@Nullable Object, V extends @Nullable Object>
LinkedHashMapV> Creates a mutable, empty, insertion-orderedLinkedHashMapinstance.static@Nullable Object, V extends @Nullable Object>
LinkedHashMapV> newLinkedHashMap(Map extends K, ? extends V> map) Creates a mutable, insertion-orderedLinkedHashMapinstance with the same mappings as the specified map.static@Nullable Object, V extends @Nullable Object>
LinkedHashMapV> newLinkedHashMapWithExpectedSize(int expectedSize) Creates aLinkedHashMapinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements without growth.Creates a mutable, emptyTreeMapinstance using the natural ordering of its elements.newTreeMap(@Nullable Comparator comparator) Creates a mutable, emptyTreeMapinstance using the given comparator.newTreeMap(SortedMap map) Creates a mutableTreeMapinstance with the same mappings as the specified map and using the same ordering as the specified map.staticComparable super K>, V extends @Nullable Object>
NavigableMapV> subMap(NavigableMap V> map, Range range) Returns a view of the portion ofmapwhose keys are contained byrange.synchronizedBiMap(BiMap V> bimap) Returns a synchronized (thread-safe) bimap backed by the specified bimap.static@Nullable Object, V extends @Nullable Object>
NavigableMapV> synchronizedNavigableMap(NavigableMap V> navigableMap) Returns a synchronized (thread-safe) navigable map backed by the specified navigable map.toImmutableEnumMap(Function super T, ? extends K> keyFunction, Function super T, ? extends V> valueFunction) Returns aCollectorthat accumulates elements into anImmutableMapwhose keys and values are the result of applying the provided mapping functions to the input elements.toImmutableEnumMap(Function super T, ? extends K> keyFunction, Function super T, ? extends V> valueFunction, BinaryOperator mergeFunction) Returns aCollectorthat accumulates elements into anImmutableMapwhose keys and values are the result of applying the provided mapping functions to the input elements.staticV> ImmutableMap V> Returns an immutable map whose keys are the distinct elements ofkeysand whose value for each key was computed byvalueFunction.staticV> ImmutableMap V> Returns an immutable map whose keys are the distinct elements ofkeysand whose value for each key was computed byvalueFunction.transformEntries(Map 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.transformEntries(NavigableMap 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.transformEntries(SortedMap 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.transformValues(Map V1> fromMap, Function super V1, V2> function) Returns a view of a map where each value is transformed by a function.transformValues(NavigableMap V1> fromMap, Function super V1, V2> function) Returns a view of a navigable map where each value is transformed by a function.transformValues(SortedMap V1> fromMap, Function super V1, V2> function) Returns a view of a sorted map where each value is transformed by a function.staticV> ImmutableMap V> uniqueIndex(Iterable values, Function super V, K> keyFunction) Returns a map with the givenvalues, indexed by keys derived from those values.staticV> ImmutableMap V> uniqueIndex(Iterator values, Function super V, K> keyFunction) Returns a map with the givenvalues, indexed by keys derived from those values.unmodifiableBiMap(BiMap extends K, ? extends V> bimap) Returns an unmodifiable view of the specified bimap.static@Nullable Object, V extends @Nullable Object>
NavigableMapV> Returns an unmodifiable view of the specified navigable map.
-
Method Details
-
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@Nullable Object, K extends Enum Collector, V> ImmutableMap toImmutableEnumMapV>> (Function super T, ? extends K> keyFunction, Function super T, ? extends V> valueFunction) Returns aCollectorthat accumulates elements into anImmutableMapwhose 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
IllegalArgumentExceptionis thrown when the collection operation is performed. (This differs from theCollectorreturned byCollectors.toMap(Function, Function), which throws anIllegalStateException.)- Since:
- 21.0
-
toImmutableEnumMap
public static@Nullable Object, K extends Enum Collector, V> ImmutableMap toImmutableEnumMapV>> (Function super T, ? extends K> keyFunction, Function super T, ? extends V> valueFunction, BinaryOperator mergeFunction) Returns aCollectorthat accumulates elements into anImmutableMapwhose 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, emptyHashMapinstance.Note: if mutability is not required, use
ImmutableMap.of()instead.Note: if
Kis anenumtype, usenewEnumMap(Class)instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
HashMapconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
HashMap
-
newHashMap
public static@Nullable Object, V extends @Nullable Object> HashMapV> newHashMap(Map extends K, ? extends V> map) Creates a mutableHashMapinstance with the same mappings as the specified map.Note: if mutability is not required, use
ImmutableMap.copyOf(Map)instead.Note: if
Kis anEnumtype, usenewEnumMap(Class)instead.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
HashMapconstructor directly, taking advantage of "diamond" syntax.- Parameters:
map- the mappings to be placed in the new map- Returns:
- a new
HashMapinitialized with the mappings frommap
-
newHashMapWithExpectedSize
public static@Nullable Object, V extends @Nullable Object> HashMapV> newHashMapWithExpectedSize(int expectedSize) Creates aHashMapinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements 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
HashMapwith enough capacity to holdexpectedSizeentries without resizing - Throws:
IllegalArgumentException- ifexpectedSizeis negative
-
newLinkedHashMap
Creates a mutable, empty, insertion-orderedLinkedHashMapinstance.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
LinkedHashMapconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
LinkedHashMap
-
newLinkedHashMap
public static@Nullable Object, V extends @Nullable Object> LinkedHashMapV> newLinkedHashMap(Map extends K, ? extends V> map) Creates a mutable, insertion-orderedLinkedHashMapinstance 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
LinkedHashMapconstructor directly, taking advantage of "diamond" syntax.- Parameters:
map- the mappings to be placed in the new map- Returns:
- a new,
LinkedHashMapinitialized with the mappings frommap
-
newLinkedHashMapWithExpectedSize
public static@Nullable Object, V extends @Nullable Object> LinkedHashMapV> newLinkedHashMapWithExpectedSize(int expectedSize) Creates aLinkedHashMapinstance, with a high enough "initial capacity" that it should holdexpectedSizeelements 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
LinkedHashMapwith enough capacity to holdexpectedSizeentries without resizing - Throws:
IllegalArgumentException- ifexpectedSizeis negative- Since:
- 19.0
-
newConcurrentMap
Creates a new emptyConcurrentHashMapinstance.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
ConcurrentHashMapconstructor directly, taking advantage of "diamond" syntax.- Since:
- 3.0
-
newTreeMap
Creates a mutable, emptyTreeMapinstance 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
TreeMapconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
TreeMap
-
newTreeMap
Creates a mutableTreeMapinstance 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
TreeMapconstructor 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
TreeMapinitialized with the mappings frommapand using the comparator ofmap
-
newTreeMap
public static@Nullable Object, K extends C, V extends @Nullable Object> TreeMapV> newTreeMap(@Nullable Comparator comparator) Creates a mutable, emptyTreeMapinstance 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
TreeMapconstructor directly, taking advantage of "diamond" syntax.- Parameters:
comparator- the comparator to sort the keys with- Returns:
- a new, empty
TreeMap
-
newEnumMap
-
newEnumMap
Creates anEnumMapwith the same mappings as the specified map.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
EnumMapconstructor directly, taking advantage of "diamond" syntax.- Parameters:
map- the map from which to initialize thisEnumMap- Returns:
- a new
EnumMapinitialized with the mappings frommap - Throws:
IllegalArgumentException- ifmis not anEnumMapinstance and contains no mappings
-
newIdentityHashMap
Creates anIdentityHashMapinstance.Note: this method is now unnecessary and should be treated as deprecated. Instead, use the
IdentityHashMapconstructor directly, taking advantage of "diamond" syntax.- Returns:
- a new, empty
IdentityHashMap
-
difference
public static@Nullable Object, V extends @Nullable Object> MapDifferenceV> 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
HashMapinstances internally, the keys of the supplied maps must be well-behaved with respect toObject.equals(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@Nullable Object, V extends @Nullable Object> MapDifferenceV> difference(Map extends K, ? extends V> left, Map extends K, ? extends V> right, Equivalence super @NonNull 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
HashMapinstances internally, the keys of the supplied maps must be well-behaved with respect toObject.equals(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@Nullable Object, V extends @Nullable Object> SortedMapDifferenceV> difference(SortedMap 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
TreeMapinstances 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
-
asMap
public static@Nullable Object, V extends @Nullable Object> MapV> asMap(Set set, Function super K, V> function) Returns a liveMapview whose keys are the contents ofsetand whose values are computed on demand usingfunction. To get an immutable copy instead, usetoMap(Iterable, Function).Specifically, for each
kin the backing set, the returned map has an entry mappingktofunction.apply(k). ThekeySet,values, andentrySetviews 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 stopnullfrom being added to the set.Warning: This method assumes that for any instance
kof key typeK,k.equals(k2)implies thatk2is also of typeK. Using a key type for which this may not hold, such asArrayList, may risk aClassCastExceptionwhen calling methods on the resulting map view.- Since:
- 14.0
-
asMap
public static@Nullable Object, V extends @Nullable Object> SortedMapV> asMap(SortedSet set, Function super K, V> function) Returns a view of the sorted set as a map, mapping keys from the set according to the specified function.Specifically, for each
kin the backing set, the returned map has an entry mappingktofunction.apply(k). ThekeySet,values, andentrySetviews 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 stopnullfrom being added to the set.Warning: This method assumes that for any instance
kof key typeK,k.equals(k2)implies thatk2is also of typeK. Using a key type for which this may not hold, such asArrayList, may risk aClassCastExceptionwhen calling methods on the resulting map view.- Since:
- 14.0
-
toMap
Returns an immutable map whose keys are the distinct elements ofkeysand 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 whethervalueFunctionwill 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
keysis 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; ... ImmutableMapcolorNames = 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 ofkeysisnull, or ifvalueFunctionproducesnullfor any key- Since:
- 14.0
-
toMap
Returns an immutable map whose keys are the distinct elements ofkeysand 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 whethervalueFunctionwill 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 ofkeysisnull, or ifvalueFunctionproducesnullfor any key- Since:
- 14.0
-
uniqueIndex
@CanIgnoreReturnValue public staticV> ImmutableMapV> uniqueIndex(Iterable 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 applyingkeyFunctionto that value. These entries appear in the same order as the input values. Example usage:Color red = new Color("red", 255, 0, 0); ... ImmutableSetallColors = ImmutableSet.of(red, green, blue); ImmutableMap 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; ... ImmutableMapcolorForName = 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 theMapkeyFunction- the function used to produce the key for each value- Returns:
- a map mapping the result of evaluating the function
keyFunctionon each value in the input collection to that value - Throws:
IllegalArgumentException- ifkeyFunctionproduces the same key for more than one value in the input collectionNullPointerException- if any element ofvaluesisnull, or ifkeyFunctionproducesnullfor any value
-
uniqueIndex
@CanIgnoreReturnValue public staticV> ImmutableMapV> uniqueIndex(Iterator 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 applyingkeyFunctionto that value. These entries appear in the same order as the input values. Example usage:Color red = new Color("red", 255, 0, 0); ... IteratorallColors = ImmutableSet.of(red, green, blue).iterator(); Map 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 theMapkeyFunction- the function used to produce the key for each value- Returns:
- a map mapping the result of evaluating the function
keyFunctionon each value in the input collection to that value - Throws:
IllegalArgumentException- ifkeyFunctionproduces the same key for more than one value in the input collectionNullPointerException- if any element ofvaluesisnull, or ifkeyFunctionproducesnullfor any value- Since:
- 10.0
-
fromProperties
Creates anImmutableMapfrom aPropertiesinstance. Properties normally derive fromMap, but they typically contain strings, which is awkward. This method lets you get a plain-old-Mapout of aProperties.- Parameters:
properties- aPropertiesobject to be converted- Returns:
- an immutable map containing all the entries in
properties - Throws:
ClassCastException- if any key inpropertiesis not aStringNullPointerException- if any key or value inpropertiesis null
-
immutableEntry
public static@Nullable Object, V extends @Nullable Object> Map.EntryV> immutableEntry(K key, V value) 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
-
asConverter
Returns aConverterthat converts values usingbimap.get(), and whose inverse view converts values usingbimap.inverse().get().To use a plain
Mapas aFunction, seeFunctions.forMap(Map)orFunctions.forMap(Map, Object).- Since:
- 16.0
-
synchronizedBiMap
public static@Nullable Object, V extends @Nullable Object> BiMapV> synchronizedBiMap(BiMap V> bimap) 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:
BiMapmap = 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.
- Parameters:
bimap- the bimap to be wrapped in a synchronized view- Returns:
- a synchronized view of the specified bimap
-
unmodifiableBiMap
public static@Nullable Object, V extends @Nullable Object> BiMapV> unmodifiableBiMap(BiMap extends K, ? extends V> bimap) 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@Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> MapV2> transformValues(Map 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:... printsMapmap = ImmutableMap.of("a", 4, "b", 9); Function sqrt = (Integer in) -> Math.sqrt(in); Map 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(Object)andMap.toString(). For this to perform well,functionshould 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@Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> SortedMapV2> transformValues(SortedMap 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:... printsSortedMapmap = ImmutableSortedMap.of("a", 4, "b", 9); Function sqrt = (Integer in) -> Math.sqrt(in); SortedMap 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(Object)andMap.toString(). For this to perform well,functionshould 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@Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> MapV2> transformEntries(Map 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(Map, Function), 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:
... printsMapoptions = ImmutableMap.of("verbose", true, "sort", false); EntryTransformer flagPrefixer = (key, value) -> value ? key : "no" + key; Map 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(Object)andObject.toString(). For this to perform well,transformershould 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
kofEntryTransformerkey typeK,k.equals(k2)implies thatk2is also of typeK. Using anEntryTransformerkey type for which this may not hold, such asArrayList, may risk aClassCastExceptionwhen calling methods on the transformed map.- Since:
- 7.0
-
transformEntries
public static@Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> SortedMapV2> transformEntries(SortedMap 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(Map, Function), 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:
... printsMapoptions = ImmutableSortedMap.of("verbose", true, "sort", false); EntryTransformer flagPrefixer = (key, value) -> value ? key : "no" + key; SortedMap transformed = Maps.transformEntries(options, flagPrefixer); System.out.println(transformed); {sort=nosort, 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(Object)andObject.toString(). For this to perform well,transformershould 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
kofEntryTransformerkey typeK,k.equals(k2)implies thatk2is also of typeK. Using anEntryTransformerkey type for which this may not hold, such asArrayList, may risk aClassCastExceptionwhen calling methods on the transformed map.- Since:
- 11.0
-
filterKeys
public static@Nullable Object, V extends @Nullable Object> MapV> filterKeys(Map V> unfiltered, Predicate super K> keyPredicate) Returns a map containing the mappings inunfilteredwhose 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
unfilteredis.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:
keyPredicatemust 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@Nullable Object, V extends @Nullable Object> SortedMapV> filterKeys(SortedMap V> unfiltered, Predicate super K> keyPredicate) Returns a sorted map containing the mappings inunfilteredwhose 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
unfilteredis.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:
keyPredicatemust 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@Nullable Object, V extends @Nullable Object> BiMapV> filterKeys(BiMap V> unfiltered, Predicate super K> keyPredicate) Returns a bimap containing the mappings inunfilteredwhose 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
unfilteredis.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:
entryPredicatemust be consistent with equals , as documented atPredicate.apply(T).- Since:
- 14.0
-
filterValues
public static@Nullable Object, V extends @Nullable Object> MapV> filterValues(Map V> unfiltered, Predicate super V> valuePredicate) Returns a map containing the mappings inunfilteredwhose 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
unfilteredis.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:
valuePredicatemust 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@Nullable Object, V extends @Nullable Object> SortedMapV> filterValues(SortedMap V> unfiltered, Predicate super V> valuePredicate) Returns a sorted map containing the mappings inunfilteredwhose 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
unfilteredis.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:
valuePredicatemust 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@Nullable Object, V extends @Nullable Object> BiMapV> filterValues(BiMap V> unfiltered, Predicate super V> valuePredicate) Returns a bimap containing the mappings inunfilteredwhose 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 anIllegalArgumentExceptionwhen 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
unfilteredis.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:
entryPredicatemust be consistent with equals , as documented atPredicate.apply(T).- Since:
- 14.0
-
filterEntries
public static@Nullable Object, V extends @Nullable Object> MapV> filterEntries(Map V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a map containing the mappings inunfilteredthat 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 anIllegalArgumentExceptionwhen 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
unfilteredis.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:
entryPredicatemust be consistent with equals, as documented atPredicate.apply(T). -
filterEntries
public static@Nullable Object, V extends @Nullable Object> SortedMapV> filterEntries(SortedMap V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a sorted map containing the mappings inunfilteredthat 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 anIllegalArgumentExceptionwhen 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
unfilteredis.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:
entryPredicatemust be consistent with equals, as documented atPredicate.apply(T).- Since:
- 11.0
-
filterEntries
public static@Nullable Object, V extends @Nullable Object> BiMapV> filterEntries(BiMap V> unfiltered, Predicate super Map.Entry V>> entryPredicate) Returns a bimap containing the mappings inunfilteredthat 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 anIllegalArgumentExceptionwhen 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
unfilteredis.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:
entryPredicatemust be consistent with equals , as documented atPredicate.apply(T).- Since:
- 14.0
-