com.google.common.collect
Class Maps

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

public final class Maps
extends java.lang.Object

Static utility methods pertaining to Map instances. Also see this class's counterparts Lists and Sets.

Author:
Kevin Bourrillion, Mike Bostock, Isaac Shum

Method Summary
static
<K,V> java.util.Map<K,V>
filterEntries(java.util.Map<K,V> unfiltered, Predicate<java.util.Map.Entry<K,V>> entryPredicate)
          Returns a map containing the mappings in unfiltered that satisfy a predicate.
static
<K,V> java.util.Map<K,V>
filterKeys(java.util.Map<K,V> unfiltered, Predicate<? super K> keyPredicate)
          Returns a map containing the mappings in unfiltered whose keys satisfy a predicate.
static
<K,V> java.util.Map<K,V>
filterValues(java.util.Map<K,V> unfiltered, Predicate<? super V> valuePredicate)
          Returns a map containing the mappings in unfiltered whose values satisfy a predicate.
static java.util.Map<java.lang.String,java.lang.String> fromProperties(java.util.Properties properties)
          Creates a Map<String, String> from a Properties instance.
static
<K,V> java.util.Map.Entry<K,V>
immutableEntry(K key, V value)
          Returns an immutable map entry with the specified key and value.
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(java.util.Map<java.lang.Class<? extends B>,B> backingMap)
          Returns a new ClassToInstanceMap instance backed by a given empty backingMap.
static
<K extends java.lang.Enum<K>,V>
java.util.EnumMap<K,V>
newEnumMap(java.lang.Class<K> type)
          Creates an EnumMap instance.
static
<K extends java.lang.Enum<K>,V>
java.util.EnumMap<K,V>
newEnumMap(java.util.Map<K,? extends V> map)
          Creates an EnumMap initialized from the specified map.
static
<K,V> java.util.HashMap<K,V>
newHashMap()
          Creates a HashMap instance.
static
<K,V> java.util.HashMap<K,V>
newHashMap(java.util.Map<? extends K,? extends V> map)
          Creates a HashMap instance with the same mappings as the specified map.
static
<K,V> java.util.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> java.util.IdentityHashMap<K,V>
newIdentityHashMap()
          Creates an IdentityHashMap instance.
static
<K,V> java.util.LinkedHashMap<K,V>
newLinkedHashMap()
          Creates an insertion-ordered LinkedHashMap instance.
static
<K,V> java.util.LinkedHashMap<K,V>
newLinkedHashMap(java.util.Map<? extends K,? extends V> map)
          Creates an insertion-ordered LinkedHashMap instance with the same mappings as the specified map.
static
<K extends java.lang.Comparable,V>
java.util.TreeMap<K,V>
newTreeMap()
          Creates a TreeMap instance using the natural ordering of its elements.
static
<C,K extends C,V>
java.util.TreeMap<K,V>
newTreeMap(java.util.Comparator<C> comparator)
          Creates a TreeMap instance using the given comparator.
static
<K,V> java.util.TreeMap<K,V>
newTreeMap(java.util.SortedMap<K,? extends V> map)
          Creates a TreeMap instance with the same mappings as the specified map and using the same ordering as 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,V1,V2> java.util.Map<K,V2>
transformValues(java.util.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,V> ImmutableMap<K,V>
uniqueIndex(java.lang.Iterable<? extends V> values, Function<? super V,K> keyFunction)
          Returns an immutable map for which the Map.values() are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.
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> java.util.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 new, empty HashMap

newHashMapWithExpectedSize

public static <K,V> java.util.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 new empty HashMap with enough capacity to hold expectedSize elements without rehashing
Throws:
java.lang.IllegalArgumentException - if expectedSize is negative

newHashMap

public static <K,V> java.util.HashMap<K,V> newHashMap(java.util.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 new HashMap initialized with the mappings from map

newLinkedHashMap

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

Returns:
a new, empty LinkedHashMap

newLinkedHashMap

public static <K,V> java.util.LinkedHashMap<K,V> newLinkedHashMap(java.util.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 new, LinkedHashMap initialized with the mappings from map

newTreeMap

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

Returns:
a new, empty TreeMap

newTreeMap

public static <K,V> java.util.TreeMap<K,V> newTreeMap(java.util.SortedMap<K,? extends V> map)
Creates a TreeMap instance with the same mappings as the specified map and using the same ordering as the specified map.

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 newly-created TreeMap initialized with the mappings from map and using the comparator of map

newTreeMap

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

Parameters:
comparator - the comparator to sort the keys with
Returns:
a new, empty TreeMap

newEnumMap

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

Parameters:
type - the key type for this map
Returns:
a new, empty EnumMap

newEnumMap

public static <K extends java.lang.Enum<K>,V> java.util.EnumMap<K,V> newEnumMap(java.util.Map<K,? extends V> map)
Creates an EnumMap initialized from the specified map.

Parameters:
map - the map from which to initialize this EnumMap
Returns:
a newly-created EnumMap initialized from the specified map
Throws:
java.lang.IllegalArgumentException - if m is not an EnumMap instance and contains no mappings

newIdentityHashMap

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

Returns:
a new, empty IdentityHashMap

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.

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 sychronized view of the specified bimap

uniqueIndex

public static <K,V> ImmutableMap<K,V> uniqueIndex(java.lang.Iterable<? extends V> values,
                                                  Function<? super V,K> keyFunction)
Returns an immutable map for which the Map.values() are the given elements in the given order, and each key is the product of invoking a supplied function on its corresponding value.

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:
java.lang.IllegalArgumentException - if keyFunction produces the same key for more than one value in the input collection
java.lang.NullPointerException - if any elements of values is null, or if keyFunction produces null for any value

fromProperties

public static java.util.Map<java.lang.String,java.lang.String> fromProperties(java.util.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. The returned map is modifiable and serializable.

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

immutableEntry

public static <K,V> java.util.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

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(java.util.Map<java.lang.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.


transformValues

public static <K,V1,V2> java.util.Map<K,V2> transformValues(java.util.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:
   Map<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(sqrt, map);
   System.out.println(transformed);
... prints {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) and Map.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.


filterKeys

public static <K,V> java.util.Map<K,V> filterKeys(java.util.Map<K,V> unfiltered,
                                                  Predicate<? super K> keyPredicate)
Returns a map containing the mappings in unfiltered whose keys satisfy a predicate. The returned map is a live view of unfiltered; changes to one affect the other.

The resulting map's keySet(), entrySet(), and values() views have iterators that don't support remove(), but all other methods are supported by the map and its views. The map's put() and putAll() methods throw an IllegalArgumentException if a key that doesn't satisfy the predicate is provided.

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

The returned map isn't threadsafe or serializable, even if 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.


filterValues

public static <K,V> java.util.Map<K,V> filterValues(java.util.Map<K,V> unfiltered,
                                                    Predicate<? super V> valuePredicate)
Returns a map containing the mappings in unfiltered whose values satisfy a predicate. The returned map is a live view of unfiltered; changes to one affect the other.

The resulting map's keySet(), entrySet(), and values() views have iterators that don't support remove(), but all other methods are supported by the map and its views. The Map.put(K, V), Map.putAll(java.util.Map), and Map.Entry.setValue(V) methods throw an IllegalArgumentException if a value that doesn't satisfy the predicate is provided.

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

The returned map isn't threadsafe or serializable, even if 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.


filterEntries

public static <K,V> java.util.Map<K,V> filterEntries(java.util.Map<K,V> unfiltered,
                                                     Predicate<java.util.Map.Entry<K,V>> entryPredicate)
Returns a map containing the mappings in unfiltered that satisfy a predicate. The returned map is a live view of unfiltered; changes to one affect the other.

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

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

The returned map isn't threadsafe or serializable, even if 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.



Copyright © 2007-2009 Google. All Rights Reserved.