com.google.common.collect
Class Maps

java.lang.Object
  extended by com.google.common.collect.Maps

public final class Maps
extends Object

Provides static methods for creating mutable Map instances easily. You can replace code like:

Map<String, Integer> map = new HashMap<String, Integer>();

with just:

Map<String, Integer> map = Maps.newHashMap();

Supported today are: HashMap, LinkedHashMap, ConcurrentHashMap, TreeMap, and EnumMap.

See also this class's counterparts Lists and Sets.

Author:
Kevin Bourrillion, Mike Bostock

Method Summary
static boolean containsEntry(Map<?,?> map, Object key, Object value)
          Returns true if map contains an entry mapping key to value.
static Map<String,String> fromProperties(Properties properties)
          Creates a Map<String, String> from a Properties instance.
static
<K,V> BiMap<K,V>
immutableBiMap()
          Returns an immutable empty BiMap instance.
static
<K,V> BiMap<K,V>
immutableBiMap(K k1, V v1)
          Creates a new immutable BiMap instance containing the given key-value pair.
static
<K,V> BiMap<K,V>
immutableBiMap(K k1, V v1, K k2, V v2)
          Creates a new immutable BiMap instance containing the given key-value pairs.
static
<K,V> BiMap<K,V>
immutableBiMap(K k1, V v1, K k2, V v2, K k3, V v3)
          Creates a new immutable BiMap instance containing the given key-value pairs.
static
<K,V> BiMap<K,V>
immutableBiMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4)
          Creates a new immutable BiMap instance containing the given key-value pairs.
static
<K,V> BiMap<K,V>
immutableBiMap(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5)
          Creates a new immutable BiMap instance containing the given key-value pairs.
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,V> BiMap<K,V>
newBiMap(Map<K,V> forward, Map<V,K> backward)
          Returns a new BiMap, backed by the two supplied empty maps.
static
<B> ClassToInstanceMap<B>
newClassToInstanceMap()
          Returns a new ClassToInstanceMap instance backed by a HashMap using the default initial capacity and load factor.
static
<B> ClassToInstanceMap<B>
newClassToInstanceMap(Map<Class<? extends B>,B> backingMap)
          Returns a new ClassToInstanceMap instance backed by a given empty backingMap.
static
<K,V> ConcurrentHashMap<K,V>
newConcurrentHashMap()
          Creates a ConcurrentHashMap instance.
static
<K extends Enum<K>,V extends Enum<V>>
EnumBiMap<K,V>
newEnumBiMap(Class<K> keyType, Class<V> valueType)
          Returns a new empty EnumBiMap using the specified key type and value type.
static
<K extends Enum<K>,V>
EnumHashBiMap<K,V>
newEnumHashBiMap(Class<K> keyType)
          Returns a new empty EnumHashBiMap using the specified key type.
static
<K extends Enum<K>,V>
EnumMap<K,V>
newEnumMap(Class<K> type)
          Creates an EnumMap instance.
static
<K,V> HashBiMap<K,V>
newHashBiMap()
          Returns a new empty HashBiMap with the default initial capacity (16) and load factor (0.75).
static
<K,V> HashMap<K,V>
newHashMap()
          Creates a HashMap instance.
static
<K,V> HashMap<K,V>
newHashMap(Map<? extends K,? extends V> map)
          Creates a HashMap instance with the same mappings as the specified map.
static
<K,V> HashMap<K,V>
newHashMapWithExpectedSize(int expectedSize)
          Creates a HashMap instance with enough capacity to hold the specified number of elements without rehashing.
static
<K,V> IdentityHashMap<K,V>
newIdentityHashMap()
          Creates an IdentityHashMap instance.
static
<K,V> LinkedHashMap<K,V>
newLinkedHashMap()
          Creates an insertion-ordered LinkedHashMap instance.
static
<K,V> LinkedHashMap<K,V>
newLinkedHashMap(Map<? extends K,? extends V> map)
          Creates an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.
static
<K extends Comparable,V>
TreeMap<K,V>
newTreeMap()
          Creates a TreeMap instance using the natural ordering of its elements.
static
<C,K extends C,V>
TreeMap<K,V>
newTreeMap(Comparator<C> comparator)
          Creates a TreeMap instance using the given comparator.
static
<K,V> SortedSet<K>
sortedKeySet(SortedMap<K,V> map)
          Returns a sorted set view of the keys contained in the specified map.
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> Map<K,V>
uniqueIndex(Collection<? extends V> values, Function<? super V,? extends K> keyFunction)
          Creates an index Map that contains the results of applying a specified function to each item in a Collection of values.
static
<K,V> Map<K,V>
uniqueIndex(Iterable<? extends V> values, Function<? super V,? extends K> keyFunction)
          Creates an index Map that contains the results of applying a specified function to each item in an Iterable of values.
static
<K,V> Map<K,V>
uniqueIndex(Iterator<? extends V> values, Function<? super V,? extends K> keyFunction)
          Creates an index Map that contains the results of applying a specified function to each item in an Iterator of values.
static
<K,V> BiMap<K,V>
unmodifiableBiMap(BiMap<K,V> bimap)
          Returns an unmodifiable view of the specified bimap.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

newHashMap

public static <K,V> HashMap<K,V> newHashMap()
Creates a HashMap instance.

Note: if K is an enum type, use newEnumMap(java.lang.Class) instead.

Note: if you don't actually need the resulting map to be mutable, use Collections.emptyMap() instead.

Returns:
a newly-created, initially-empty HashMap

newHashMapWithExpectedSize

public static <K,V> HashMap<K,V> newHashMapWithExpectedSize(int expectedSize)
Creates a HashMap instance with enough capacity to hold the specified number of elements without rehashing.

Parameters:
expectedSize - the expected size
Returns:
a newly-created HashMap, initially empty, with enough capacity to hold expectedSize elements without rehashing
Throws:
IllegalArgumentException - if expectedSize is negative

newHashMap

public static <K,V> HashMap<K,V> newHashMap(Map<? extends K,? extends V> map)
Creates a HashMap instance with the same mappings as the specified map.

Note: if K is an Enum type, use newEnumMap(java.lang.Class) instead.

Parameters:
map - the mappings to be placed in the new map
Returns:
a newly-created HashMap initialized with the mappings from map

newLinkedHashMap

public static <K,V> LinkedHashMap<K,V> newLinkedHashMap()
Creates an insertion-ordered LinkedHashMap instance.

Returns:
a newly-created, initially-empty LinkedHashMap

newLinkedHashMap

public static <K,V> LinkedHashMap<K,V> newLinkedHashMap(Map<? extends K,? extends V> map)
Creates an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.

Parameters:
map - the mappings to be placed in the new map
Returns:
a newly-created, LinkedHashMap initialized with the mappings from map

newConcurrentHashMap

public static <K,V> ConcurrentHashMap<K,V> newConcurrentHashMap()
Creates a ConcurrentHashMap instance.

Returns:
a newly-created, initially-empty ConcurrentHashMap

newTreeMap

public static <K extends Comparable,V> TreeMap<K,V> newTreeMap()
Creates a TreeMap instance using the natural ordering of its elements.

Returns:
a newly-created, initially-empty TreeMap

newTreeMap

public static <C,K extends C,V> TreeMap<K,V> newTreeMap(@Nullable
                                                        Comparator<C> comparator)
Creates a TreeMap instance using the given comparator.

Parameters:
comparator - the Comparator to sort the keys with
Returns:
a newly-created, initially-empty TreeMap

newEnumMap

public static <K extends Enum<K>,V> EnumMap<K,V> newEnumMap(Class<K> type)
Creates an EnumMap instance.

Parameters:
type - the key type for this map
Returns:
a newly-created, initially-empty EnumMap

newIdentityHashMap

public static <K,V> IdentityHashMap<K,V> newIdentityHashMap()
Creates an IdentityHashMap instance.

Returns:
a newly-created, initially-empty IdentityHashMap

containsEntry

public static boolean containsEntry(Map<?,?> map,
                                    @Nullable
                                    Object key,
                                    @Nullable
                                    Object value)
Returns true if map contains an entry mapping key to value. If you are not concerned with null-safety you can simply use map.get(key).equals(value).


immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap()
Returns an immutable empty BiMap instance.


immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap(@Nullable
                                              K k1,
                                              @Nullable
                                              V v1)
Creates a new immutable BiMap instance containing the given key-value pair.


immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap(@Nullable
                                              K k1,
                                              @Nullable
                                              V v1,
                                              @Nullable
                                              K k2,
                                              @Nullable
                                              V v2)
Creates a new immutable BiMap instance containing the given key-value pairs.

See Also:
ImmutableBiMapBuilder

immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap(@Nullable
                                              K k1,
                                              @Nullable
                                              V v1,
                                              @Nullable
                                              K k2,
                                              @Nullable
                                              V v2,
                                              @Nullable
                                              K k3,
                                              @Nullable
                                              V v3)
Creates a new immutable BiMap instance containing the given key-value pairs.

See Also:
ImmutableBiMapBuilder

immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap(@Nullable
                                              K k1,
                                              @Nullable
                                              V v1,
                                              @Nullable
                                              K k2,
                                              @Nullable
                                              V v2,
                                              @Nullable
                                              K k3,
                                              @Nullable
                                              V v3,
                                              @Nullable
                                              K k4,
                                              @Nullable
                                              V v4)
Creates a new immutable BiMap instance containing the given key-value pairs.

See Also:
ImmutableBiMapBuilder

immutableBiMap

public static <K,V> BiMap<K,V> immutableBiMap(@Nullable
                                              K k1,
                                              @Nullable
                                              V v1,
                                              @Nullable
                                              K k2,
                                              @Nullable
                                              V v2,
                                              @Nullable
                                              K k3,
                                              @Nullable
                                              V v3,
                                              @Nullable
                                              K k4,
                                              @Nullable
                                              V v4,
                                              @Nullable
                                              K k5,
                                              @Nullable
                                              V v5)
Creates a new immutable BiMap instance containing the given key-value pairs.

See Also:
ImmutableBiMapBuilder

synchronizedBiMap

public static <K,V> BiMap<K,V> synchronizedBiMap(BiMap<K,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:

  Bimap<K,V> m = Maps.synchronizedBiMap(
      new HashBiMap<K,V>());
   ...
  Set<K> s = m.keySet();  // Needn't be in synchronized block
   ...
  synchronized (m) {  // Synchronizing on m, not s!
    Iterator<K> i = s.iterator(); // Must be in synchronized block
    while (i.hasNext()) {
      foo(i.next());
    }
  }
Failure to follow this advice may result in non-deterministic behavior.

Parameters:
bimap - the bimap to be wrapped in a synchronized view
Returns:
a sychronized view of the specified bimap

sortedKeySet

public static <K,V> SortedSet<K> sortedKeySet(SortedMap<K,V> map)
Returns a sorted set view of the keys contained in the specified map. The set is backed by the map, so changes to the map are reflected in the set, and vice versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, removeAll, and clear operations. It does not support the add or addAll operations.

Returns:
a sorted set view of the keys contained in the specified map.

uniqueIndex

public static <K,V> Map<K,V> uniqueIndex(Iterable<? extends V> values,
                                         Function<? super V,? extends K> keyFunction)
Creates an index Map that contains the results of applying a specified function to each item in an Iterable of values. Each value will be stored as a value in the resulting map. The key used to store that value in the map will be the result of calling the function on that value. Neither keys nor values are allowed to be null. It is an error if the function produces the same key for more than one value in the input collection.

Parameters:
values - the values to use when constructing the Map
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 - if keyFunction produces the same key for more than one value in the input collection
NullPointerException - if any elements of values are null, or if keyFunction produces null for any value

uniqueIndex

public static <K,V> Map<K,V> uniqueIndex(Collection<? extends V> values,
                                         Function<? super V,? extends K> keyFunction)
Creates an index Map that contains the results of applying a specified function to each item in a Collection of values. Each value will be stored as a value in the resulting map. The key used to store that value in the map will be the result of calling the function on that value. Neither keys nor values are allowed to be null. It is an error if the function produces the same key for more than one value in the input collection.

Parameters:
values - the values to use when constructing the Map
keyFunction - the function used to produce the key for each value
Returns:
Map mapping the result of evaluating the function keyFunction on each value in the input collection to that value
Throws:
IllegalArgumentException - if keyFunction produces the same key for more than one value in the input collection
NullPointerException - if any elements of values are null, or if keyFunction produces null for any value

uniqueIndex

public static <K,V> Map<K,V> uniqueIndex(Iterator<? extends V> values,
                                         Function<? super V,? extends K> keyFunction)
Creates an index Map that contains the results of applying a specified function to each item in an Iterator of values. Each value will be stored as a value in the resulting map. The key used to store that value in the map will be the result of calling the function on that value. Neither keys nor values are allowed to be null. It is an error if the function produces the same key for more than one value in the input collection.

Parameters:
values - the values to use when constructing the Map
keyFunction - the function used to produce the key for each value
Returns:
Map mapping the result of evaluating the function keyFunction on each value in the input collection to that value
Throws:
IllegalArgumentException - if keyFunction produces the same key for more than one value in the input collection
NullPointerException - if any elements of values are null, or if keyFunction produces null for any value

fromProperties

public static Map<String,String> fromProperties(Properties properties)
Creates a Map<String, String> from a Properties instance. Properties normally derive from Map<Object, Object>, but they typically contain strings, which is awkward. This method lets you get a plain-old-Map out of a Properties. The returned map won't include any null keys or values.

Parameters:
properties - a Properties object to be converted
Returns:
a map containing all the entries in properties

immutableEntry

public static <K,V> Map.Entry<K,V> immutableEntry(@Nullable
                                                  K key,
                                                  @Nullable
                                                  V value)
Returns an immutable map entry with the specified key and value. The Map.Entry.setValue(V) operation throws an UnsupportedOperationException.

The returned entry is serializable.

Parameters:
key - the key to be associated with the returned entry
value - the value to be associated with the returned entry

newHashBiMap

public static <K,V> HashBiMap<K,V> newHashBiMap()
Returns a new empty HashBiMap with the default initial capacity (16) and load factor (0.75).


newEnumHashBiMap

public static <K extends Enum<K>,V> EnumHashBiMap<K,V> newEnumHashBiMap(Class<K> keyType)
Returns a new empty EnumHashBiMap using the specified key type.

Parameters:
keyType - the key type

newEnumBiMap

public static <K extends Enum<K>,V extends Enum<V>> EnumBiMap<K,V> newEnumBiMap(Class<K> keyType,
                                                                                Class<V> valueType)
Returns a new empty EnumBiMap using the specified key type and value type.

Parameters:
keyType - the key type
valueType - the value type

newBiMap

public static <K,V> BiMap<K,V> newBiMap(Map<K,V> forward,
                                        Map<V,K> backward)
Returns a new BiMap, backed by the two supplied empty maps. The caller surrenders control of these maps and should not retain any references to either.

The returned bimap will be serializable if both of the specified maps are serializable.

Parameters:
forward - an empty map to be used for associating keys with values
backward - an empty map to be used for associating values with keys
Throws:
IllegalArgumentException - if either map is nonempty

unmodifiableBiMap

public static <K,V> BiMap<K,V> unmodifiableBiMap(BiMap<K,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 attemps to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

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

newClassToInstanceMap

public static <B> ClassToInstanceMap<B> newClassToInstanceMap()
Returns a new ClassToInstanceMap instance backed by a HashMap using the default initial capacity and load factor.


newClassToInstanceMap

public static <B> ClassToInstanceMap<B> newClassToInstanceMap(Map<Class<? extends B>,B> backingMap)
Returns a new ClassToInstanceMap instance backed by a given empty backingMap. The caller surrenders control of the backing map, and thus should not allow any direct references to it to remain accessible.