public interface Map
GDK enhancements for Map.
| Modifiers | Name | Description |
|---|---|---|
static interface |
Map.Entry |
GDK enhancements for Entry. |
| Type Params | Return Type | Name and description |
|---|---|---|
<K, V> |
public boolean |
any(Closure<?> predicate)Iterates over the entries of a map, and checks whether a predicate is valid for at least one entry. |
|
public boolean |
asBoolean()Coerce a map instance to a boolean value. |
<K, V> |
public Map<K, V> |
asChecked(Class<K> keyType, Class<V> valueType)Creates a checked view of a Map. |
<K, V> |
public Map<K, V> |
asImmutable()A convenience method for creating an immutable Map. |
<K, V> |
public Map<K, V> |
asSynchronized()Creates a synchronized view of a Map. |
<T> |
public T |
asType(Class<T> clazz)Coerces this map to the given type, using the map's keys as the public method names, and values as the implementation. |
<K, V> |
public Map<K, V> |
asUnmodifiable()Creates an unmodifiable view of a Map. |
<T, K, V, C> |
public C |
collect(C collector, Closure<? extends T> transform)Iterates through this Map transforming each map entry into a new value using the transform closure
returning the collector with all transformed values added to it. |
<T, K, V> |
public List<T> |
collect(Closure<T> transform)Iterates through this Map transforming each map entry into a new value using the transform closure
returning a list of transformed values. |
<K, V, X, Y> |
public Map<K, V> |
collectEntries(Map<K, V> collector, Closure<?> transform)Iterates through this Map transforming each map entry using the transform closure
returning a map of the transformed entries. |
<K, V, X, Y> |
public Map<K, V> |
collectEntries(Closure<?> transform)Iterates through this Map transforming each entry using the transform closure
and returning a map of the transformed entries. |
<K, V, X, Y> |
public Map<K, V> |
collectEntries(Map<K, V> collector, Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform)A variant of collectEntries for Maps with separate functions for transforming the keys and values. |
<K, V, X, Y> |
public Map<K, V> |
collectEntries(Function<? super X, K> keyTransform, Function<? super Y, V> valueTransform)A variant of collectEntries for Maps with separate functions for transforming the keys and values. |
<K, V> |
public Map<K, V> |
collectKeys(Map<K, V> collector, Function<? super K, K> keyTransform)Transform a Maps' keys leaving the values unchanged. |
<K, V> |
public Map<K, V> |
collectKeys(Function<? super K, K> keyTransform)Transform a Maps' keys leaving the values unchanged. |
<T, K, V, C> |
public C |
collectMany(C collector, Closure<? extends Collection<? extends T>> projection)Projects each item from a source map to a result collection and concatenates (flattens) the resulting collections adding them into the collector. |
<T, K, V> |
public List<T> |
collectMany(Closure<? extends Collection<? extends T>> projection)Projects each item from a source map to a result collection and concatenates (flattens) the resulting collections adding them into a collection. |
<K, V> |
public Map<K, V> |
collectValues(Map<K, V> collector, Function<? super V, V> valueTransform)Transform a Maps' values leaving the keys unchanged. |
<K, V> |
public Map<K, V> |
collectValues(Function<? super V, V> valueTransform)Transform a Maps' values leaving the keys unchanged. |
<K, V> |
public Number |
count(Closure<?> closure)Counts the number of occurrences which satisfy the given closure from inside this map. |
<K, V, E> |
public E |
count(E initialCount, Closure<?> closure)Counts the number of occurrences which satisfy the given closure from inside this map. |
<K, U, V> |
public Map<K, Integer> |
countBy(Closure<K> closure)Groups the members of a map into groups determined by the supplied mapping closure and counts the frequency of the created groups. |
<K, V> |
public Map<K, V> |
drop(int num)Drops the given number of key/value pairs from the head of this map if they are available. |
<K, V> |
public Map<K, V> |
dropWhile(Closure condition)Create a suffix of the given Map by dropping as many entries as possible from the front of the original Map such that calling the given closure condition evaluates to true when passed each of the dropped entries (or key/value pairs). |
<K, V> |
public Map<K, V> |
each(Closure<?> closure)Allows a Map to be iterated through using a closure. |
<K, V> |
public Map<K, V> |
eachWithIndex(Closure<?> closure)Allows a Map to be iterated through using a closure. |
|
public boolean |
equals(Map other)Compares two Maps treating coerced numerical values as identical. |
<K, V> |
public boolean |
every(Closure predicate)Iterates over the entries of a map, and checks whether a predicate is valid for all entries. |
<K, V> |
public Entry<K, V> |
find(Closure<?> closure)Finds the first entry matching the closure condition. |
<K, V> |
public Map<K, V> |
findAll(Closure closure)Finds all entries matching the closure condition. |
<T, K, V> |
public T |
findResult(Closure<T> condition)Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned. |
<T, U, V, A, B> |
public T |
findResult(U defaultResult, Closure<V> condition)Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned. |
<T, K, V> |
public Collection<T> |
findResults(Closure<T> filteringTransform)Iterates through the map transforming items using the supplied closure and collecting any non-null results. |
<K, V> |
public V |
get(K key, V defaultValue)Looks up an item in a Map for the given key and returns the corresponding value. |
<K, V> |
public V |
getAt(Object key)Support the subscript operator for a Map. |
|
public String |
groovyToString()Returns Groovy's default string representation for a Map. |
<G, K, V> |
public Map<G, Map<K, V>> |
groupBy(Closure<G> closure)Groups the members of a map into sub maps determined by the supplied mapping closure. |
|
public Map<Object, Map> |
groupBy(Object closures)Groups the members of a map into sub maps determined by the supplied mapping closures. |
|
public Map<Object, Map> |
groupBy(List<Closure> closures)Groups the members of a map into sub maps determined by the supplied mapping closures. |
<T, K> |
public Map<K, List<T>> |
groupByMany()Groups all keys from the map into (sub)groups determined by the values. |
<G, K, V> |
public Map<G, List<Entry<K, V>>> |
groupEntriesBy(Closure<G> closure)Groups all map entries into groups determined by the supplied mapping closure. |
<K, V, T, U, W> |
public T |
inject(U initialValue, Closure<W> closure)Iterates through the given map, passing in the initial value to the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value). |
<K, V, T, U, W> |
public List<T> |
injectAll(U initialValue, Closure<W> closure)Iterates through the given map, passing in the initial value to the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value) and then similarly for other map entries. |
<K, V> |
public Map<K, V> |
intersect(Map<K, V> right)Create a Map composed of the intersection of both maps. |
|
public boolean |
isCase(Object switchValue)Special 'case' implementation for maps which tests if the 'switch' operand exists in the key set. |
|
public boolean |
isNotCase(Object switchValue)
|
<K, V> |
public boolean |
isSorted()Determines if the Map entries are sorted. |
<K, V> |
public boolean |
isSorted(Comparator<Entry<K, V>> comparator)Determines if the Map entries are sorted according to the given Comparator. |
<K, V> |
public boolean |
isSorted(Closure condition)Determines if the Map entries are sorted using the given Closure to determine order. |
<K, V> |
public Iterator<Entry<K, V>> |
iterator()Returns an Iterator for the given Map's entry set. |
<K, V> |
public Map<K, V> |
leftShift(Entry<K, V> entry)Overloads the left shift operator to provide an easy way to append Map.Entry values to a Map. |
<K, V> |
public Map<K, V> |
leftShift(Map<K, V> other)Overloads the left shift operator to provide an easy way to put one maps entries into another map. |
<K, V> |
public Entry<K, V> |
max(Closure closure)Selects an entry in the map having the maximum calculated value as determined by the supplied closure. |
<K, V> |
public Entry<K, V> |
min(Closure closure)Selects an entry in the map having the minimum calculated value as determined by the supplied closure. |
<K, V> |
public Map<K, V> |
minus(Map removeMe)Create a Map composed of the entries of the first map minus the entries of the given map. |
<K, V> |
public Map<K, V> |
plus(Map<K, V> right)Returns a new Map containing all entries from left and right,
giving precedence to right. |
<K, V> |
public Map<K, V> |
plus(Collection<? extends Entry<? extends K, ? extends V>> entries)Returns a new Map containing all entries from self and entries,
giving precedence to entries. |
|
public String |
plus(String right)Appends a String to the literal of the Map instance. |
|
public String |
plus(GString right)Appends a GString to the literal of the Map instance. |
<K, V> |
public Map<K, V> |
putAll(Collection<? extends Entry<? extends K, ? extends V>> entries)Provides an easy way to append multiple Map.Entry values to a Map. |
<K, V> |
public V |
putAt(K key, V value)A helper method to allow maps to work with subscript operators |
<K, V> |
public boolean |
removeAll(Closure condition)Modifies this map by removing the elements that are matched according to the specified closure condition. |
<K, V> |
public boolean |
retainAll(Closure condition)Modifies this map so that it retains only its elements that are matched according to the specified closure condition. |
<K, V> |
public Map<K, V> |
reverseEach(Closure<?> closure)Allows a Map to be iterated through in reverse order using a closure. |
<K, V> |
public Map<K, V> |
sort(Closure closure)Sorts the elements from the given map into a new ordered map using the closure as a comparator to determine the ordering. |
<K, V> |
public Map<K, V> |
sort(Comparator<? super K> comparator)Sorts the elements from the given map into a new ordered Map using the specified key comparator to determine the ordering. |
<K, V> |
public Map<K, V> |
sort()Sorts the elements from the given map into a new ordered Map using the natural ordering of the keys to determine the ordering. |
|
public SpreadMap |
spread()Synonym for Map.toSpreadMap. |
<K, V> |
public Map<K, V> |
subMap(Collection<K> keys)Creates a sub-Map containing the given keys. |
<K, V> |
public Map<K, V> |
subMap(K[] keys)Creates a sub-Map containing the given keys. |
<K, V> |
public Map<K, V> |
take(int num)Returns a new map containing the first num elements from the head of this map.
|
<K, V> |
public Map<K, V> |
takeWhile(Closure condition)Returns the longest prefix of this Map where each entry (or key/value pair) when passed to the given closure evaluates to true. |
|
public String |
toMapString()Returns the string representation of this map. |
|
public String |
toMapString(int maxSize)Returns the string representation of this map. |
<K, V> |
public Map<K, V> |
toSorted()Sorts the elements from the given map into a new ordered map using a NumberAwareComparator on map entry values to determine the resulting order. |
<K, V> |
public Map<K, V> |
toSorted(Comparator<Entry<K, V>> comparator)Sorts the elements from the given map into a new ordered map using the supplied comparator to determine the ordering. |
<K, V> |
public Map<K, V> |
toSorted(Closure condition)Sorts the elements from the given map into a new ordered map using the supplied Closure condition as a comparator to determine the ordering. |
|
public SpreadMap |
toSpreadMap()Returns a new SpreadMap from this map. |
<K, V> |
public Map<K, V> |
withDefault(Closure<V> init)Wraps a map using the decorator pattern with a wrapper that intercepts all calls to get(key). |
<K, V> |
public Map<K, V> |
withDefault(boolean autoGrow, boolean autoShrink, Closure<V> init)Wraps a map using the decorator pattern with a wrapper that intercepts all calls to get(key) and put(key, value).
|
Iterates over the entries of a map, and checks whether a predicate is valid for at least one entry. If the closure takes one parameter then it will be passed the Map.Entry otherwise if the closure takes two parameters then it will be passed the key and the value.
assert [2:3, 4:5, 5:10].any { key, value -> key * 2 == value }
assert ![2:3, 4:5, 5:10].any { entry -> entry.key == entry.value * 2 }
predicate - the 1 or 2 arg closure predicate used for matchingCoerce a map instance to a boolean value. A map is coerced to false if it's empty, and to true otherwise.
assert [:] as Boolean == false
assert [a:2] as Boolean == true
Creates a checked view of a Map.
A convenience method for creating an immutable Map.
Creates a synchronized view of a Map.
Coerces this map to the given type, using the map's keys as the public method names, and values as the implementation. Typically the value would be a closure which behaves like the method implementation.
clazz - the target typeCreates an unmodifiable view of a Map.
Iterates through this Map transforming each map entry into a new value using the transform closure
returning the collector with all transformed values added to it.
assert [a:1, b:2].collect(new HashSet()) { key, value -> key * value } == ["a", "bb"] as Set
assert [3:20, 2:30].collect(new HashSet()) { entry -> entry.key * entry.value } == [60] as Set
collector - the Collection to which transformed values are addedtransform - the transformation closure which can take one (Map.Entry) or two (key, value) parameters Iterates through this Map transforming each map entry into a new value using the transform closure
returning a list of transformed values.
assert [a:1, b:2].collect { key, value -> key * value } == ["a", "bb"]
assert [3:20, 2:30].collect { entry -> entry.key * entry.value } == [60, 60]
transform - the transformation closure which can take one (Map.Entry) or two (key, value) parameters Iterates through this Map transforming each map entry using the transform closure
returning a map of the transformed entries.
assert [a:1, b:2].collectEntries([:]) { k, v -> Map.entry(v, k) } == [1:'a', 2:'b']
assert [a:1, b:2].collectEntries([30:'C']) { key, value -> [(value*10): key.toUpperCase()] } == [10:'A', 20:'B', 30:'C']
Note: When using the list-style of result, the behavior is 'def (key, value) = listResultFromClosure'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
If your collector Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
collector - the Map into which the transformed entries are puttransform - the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
should return a Map.Entry, a Map or a two-element list containing the resulting key and value Iterates through this Map transforming each entry using the transform closure
and returning a map of the transformed entries.
assert [a:1, b:2].collectEntries { key, value -> [value, key] } == [1:'a', 2:'b']
assert [a:1, b:2].collectEntries { key, value -> [(value*10): key.toUpperCase()] } == [10:'A', 20:'B']
Note: When using the list-style of result, the behavior is 'def (key, value) = listResultFromClosure'.
While we strongly discourage using a list of size other than 2, Groovy's normal semantics apply in this case;
throwing away elements after the second one and using null for the key or value for the case of a shortened list.
If your Map doesn't support null keys or values, you might get a runtime error, e.g. NullPointerException or IllegalArgumentException.
transform - the closure used for transforming, which can take one (Map.Entry) or two (key, value) parameters and
should return a Map.Entry, a Map or a two-element list containing the resulting key and valueA variant of collectEntries for Maps with separate functions for transforming the keys and values. The supplied collector map is used as the destination for transformed entries.
collector - the Map into which the transformed entries are putkeyTransform - a function for transforming Map keysvalueTransform - a function for transforming Map valuesA variant of collectEntries for Maps with separate functions for transforming the keys and values.
keyTransform - a function for transforming Map keysvalueTransform - a function for transforming Map valuesTransform a Maps' keys leaving the values unchanged. Similar to Iterable.withCollectedKeys but for Maps.
def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
def firstLetter = (s) -> s[0]
assert lengths.collectKeys([C:7], firstLetter) == [C:7, G:6, J:4, K:6, S:5]
collector - the Map into which the transformed entries are putkeyTransform - a function for transforming Map keysTransform a Maps' keys leaving the values unchanged. Similar to Iterable.withCollectedKeys but for Maps.
def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
def firstLetter = (s) -> s[0]
assert lengths.collectKeys(firstLetter) == [G:6, J:4, K:6, S:5]
keyTransform - a function for transforming Map keys Projects each item from a source map to a result collection and concatenates (flattens) the resulting
collections adding them into the collector.
def map = [bread:3, milk:5, butter:2]
def result = map.collectMany(['x']){ k, v -> if (k.startsWith('b')) k.toList() }
assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
collector - an initial collection to add the projected items toprojection - a projecting Closure returning a collection of itemsProjects each item from a source map to a result collection and concatenates (flattens) the resulting collections adding them into a collection.
def map = [bread:3, milk:5, butter:2]
def result = map.collectMany{ k, v -> k.startsWith('b') ? k.toList() : [] }
assert result == ['b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
projection - a projecting Closure returning a collection of itemsTransform a Maps' values leaving the keys unchanged. Similar to Iterable.withCollectedValues but for Maps.
def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
def squared = (e) -> e ** 2
assert lengths.collectValues([Clojure:49], squared) ==
[Clojure:49, Groovy:36, Java:16, Kotlin:36, Scala:25]
collector - the Map into which the transformed entries are putvalueTransform - a function for transforming Map valuesTransform a Maps' values leaving the keys unchanged. Similar to Iterable.withCollectedValues but for Maps.
def lengths = [Groovy:6, Java:4, Kotlin:6, Scala:5]
def squared = (e) -> e ** 2
assert lengths.collectValues(squared) == [Groovy:36, Java:16, Kotlin:36, Scala:25]
valueTransform - a function for transforming Map valuesCounts the number of occurrences which satisfy the given closure from inside this map. If the closure takes one parameter then it will be passed the Map.Entry. Otherwise, the closure should take two parameters and will be passed the key and value.
Example usage:
assert [a:1, b:1, c:2, d:2].count{ k,v -> k == 'a' || v == 2 } == 3
closure - a 1 or 2 arg Closure condition applying on the entriesCounts the number of occurrences which satisfy the given closure from inside this map. If the closure takes one parameter then it will be passed the Map.Entry. Otherwise, the closure should take two parameters and will be passed the key and value.
Example usage:
assert [a:1, b:1, c:2, d:2].count(100G){ k,v -> k == 'a' || v == 2 } == 103G
initialCount - start counting from this valueclosure - a 1 or 2 arg Closure condition applying on the entriesGroups the members of a map into groups determined by the supplied mapping closure and counts the frequency of the created groups. The closure will be passed a Map.Entry or key and value (depending on the number of parameters the closure accepts) and should return the key that each item should be grouped under. The resulting map will have an entry for each 'group' key returned by the closure, with values being the frequency counts for that 'group'.
def result = [a:1,b:2,c:3,d:4,e:5].countBy { it.value % 2 }
assert result == [0:2, 1:3]
closure - a closure mapping entries to frequency count keysDrops the given number of key/value pairs from the head of this map if they are available.
def strings = [ 'a':10, 'b':20, 'c':30 ]
assert strings.drop( 0 ) == [ 'a':10, 'b':20, 'c':30 ]
assert strings.drop( 2 ) == [ 'c':30 ]
assert strings.drop( 5 ) == [:]
If the map instance does not have ordered keys, then this function could drop a random num
entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
num - the number of elements to drop from this mapnum ones, or else the empty map, if this map has
less than num elements.Create a suffix of the given Map by dropping as many entries as possible from the front of the original Map such that calling the given closure condition evaluates to true when passed each of the dropped entries (or key/value pairs).
def shopping = [milk:1, bread:2, chocolate:3]
assert shopping.dropWhile{ it.key.size() < 6 } == [chocolate:3]
assert shopping.dropWhile{ it.value % 2 } == [bread:2, chocolate:3]
assert shopping.dropWhile{ k, v -> k.size() + v <= 7 } == [chocolate:3]
If the map instance does not have ordered keys, then this function could appear to drop random
entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
condition - a 1 (or 2) arg Closure that must evaluate to true for the
entry (or key and value) to continue dropping elementsAllows a Map to be iterated through using a closure. If the closure takes one parameter then it will be passed the Map.Entry otherwise if the closure takes two parameters then it will be passed the key and the value.
def result = ""
[a:1, b:3].each { key, value -> result += "$key$value" }
assert result == "a1b3"
def result = ""
[a:1, b:3].each { entry -> result += entry }
assert result == "a=1b=3"
In general, the order in which the map contents are processed
cannot be guaranteed. In practise, specialized forms of Map,
e.g. a TreeMap will have its contents processed according to
the natural ordering of the map.
closure - the 1 or 2 arg closure applied on each entry of the mapAllows a Map to be iterated through using a closure. If the closure takes two parameters then it will be passed the Map.Entry and the item's index (a counter starting at zero) otherwise if the closure takes three parameters then it will be passed the key, the value, and the index.
def result = ""
[a:1, b:3].eachWithIndex { key, value, index -> result += "$index($key$value)" }
assert result == "0(a1)1(b3)"
def result = ""
[a:1, b:3].eachWithIndex { entry, index -> result += "$index($entry)" }
assert result == "0(a=1)1(b=3)"
closure - a 2 or 3 arg Closure to operate on each itemCompares two Maps treating coerced numerical values as identical.
Example usage:
assert [a:2, b:3] == [a:2L, b:3.0]
other - the Map being compared toIterates over the entries of a map, and checks whether a predicate is valid for all entries. If the closure takes one parameter then it will be passed the Map.Entry otherwise if the closure takes two parameters then it will be passed the key and the value.
def map = [a:1, b:2.0, c:2L]
assert !map.every { key, value -> value instanceof Integer }
assert map.every { entry -> entry.value instanceof Number }
predicate - the 1 or 2 arg Closure predicate used for matchingFinds the first entry matching the closure condition. If the closure takes two parameters, the entry key and value are passed. If the closure takes one parameter, the Map.Entry object is passed.
assert [a:1, b:3].find { it.value == 3 }.key == "b"
closure - a 1 or 2 arg Closure conditionFinds all entries matching the closure condition. If the closure takes one parameter then it will be passed the Map.Entry. Otherwise if the closure should take two parameters, which will be the key and the value.
If the self map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
Example usage:
def result = [a:1, b:2, c:4, d:5].findAll { it.value % 2 == 0 }
assert result.every { it instanceof Map.Entry }
assert result*.key == ["b", "c"]
assert result*.value == [2, 4]
closure - a 1 or 2 arg Closure condition applying on the entriesReturns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned. If the closure takes two parameters, the entry key and value are passed. If the closure takes one parameter, the Map.Entry object is passed.
assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
assert null == [a:1, b:3].findResult { if (it.value == 9) return "Found ${it.key}:${it.value}" }
assert "Found a:1" == [a:1, b:3].findResult { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
condition - a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returnedReturns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned. If the closure takes two parameters, the entry key and value are passed. If the closure takes one parameter, the Map.Entry object is passed.
assert "Found b:3" == [a:1, b:3].findResult("default") { if (it.value == 3) return "Found ${it.key}:${it.value}" }
assert "default" == [a:1, b:3].findResult("default") { if (it.value == 9) return "Found ${it.key}:${it.value}" }
assert "Found a:1" == [a:1, b:3].findResult("default") { k, v -> if (k.size() + v == 2) return "Found $k:$v" }
defaultResult - an Object that should be returned if all closure results are nullcondition - a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returnedIterates through the map transforming items using the supplied closure and collecting any non-null results. If the closure takes two parameters, the entry key and value are passed. If the closure takes one parameter, the Map.Entry object is passed.
Example:
def map = [a:1, b:2, hi:2, cat:3, dog:2]
def result = map.findResults { k, v -> k.size() == v ? "Found $k:$v" : null }
assert result == ["Found a:1", "Found hi:2", "Found cat:3"]
filteringTransform - a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discardedLooks up an item in a Map for the given key and returns the corresponding value. If there is no entry for the given key return instead the default value and also add the key and default value to the map.
def map=[:]
map.get("a", []) << 5
assert map == [a:[5]]
For a method which doesn't mutate the map, consider instead using Map.getOrDefault
or consider using Groovy's MapWithDefault often instantiated using Map.withDefault
or with more options Map.withDefault.
key - the key to look up the valuedefaultValue - the value to return and add to the map for this key if
there is no entry for the given keySupport the subscript operator for a Map.
def map = [1:10]
assert map[1] == 10
key - an Object as a key for the map Returns Groovy's default string representation for a Map.
This is used by Groovy's formatting infrastructure (e.g., GString interpolation,
println, assert messages). By default, it delegates to
FormatHelper#toMapString(Map)#toMapString(Map).
assert [a:1, b:2].groovyToString() == '[a:1, b:2]'
If disabled, e.g. via -Dgroovy.extension.disable=groovyToString(Map),
the normal map toString() is used instead.
Alternatively, you have the option to provide a replacement extension method in an extension module
to customize how maps are displayed throughout Groovy.
Groups the members of a map into sub maps determined by the supplied mapping closure. The closure will be passed a Map.Entry or key and value (depending on the number of parameters the closure accepts) and should return the key that each item should be grouped under. The resulting map will have an entry for each 'group' key returned by the closure, with values being the map members from the original map that belong to each group. (If instead of a map, you want a list of map entries use {code}groupEntriesBy{code}.)
If the self map is one of TreeMap, Hashtable or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy { it.value % 2 }
assert result == [0:[b:2, d:4, f:6], 1:[a:1, c:3, e:5]]
closure - a closure mapping entries on keys Groups the members of a map into sub maps determined by the supplied
mapping closures. Each closure will be passed a Map.Entry or key and
value (depending on the number of parameters the closure accepts) and
should return the key that each item should be grouped under. The
resulting map will have an entry for each 'group path' returned by all
closures, with values being the map members from the original map that
belong to each such 'group path'.
If the self map is one of TreeMap, Hashtable, or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy({ it.value % 2 }, { it.key.next() })
assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]
If an empty array of closures is supplied the IDENTITY Closure will be used.
closures - an array of closures that map entries on keys Groups the members of a map into sub maps determined by the supplied
mapping closures. Each closure will be passed a Map.Entry or key and
value (depending on the number of parameters the closure accepts) and
should return the key that each item should be grouped under. The
resulting map will have an entry for each 'group path' returned by all
closures, with values being the map members from the original map that
belong to each such 'group path'.
If the self map is one of TreeMap, Hashtable, or Properties,
the returned Map will preserve that type, otherwise a LinkedHashMap will
be returned.
def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupBy([{ it.value % 2 }, { it.key.next() }])
assert result == [1:[b:[a:1], d:[c:3], f:[e:5]], 0:[c:[b:2], e:[d:4], g:[f:6]]]
If an empty list of closures is supplied the IDENTITY Closure will be used.
closures - a list of closures that map entries on keysGroups all keys from the map into (sub)groups determined by the values. Each key will be grouped under each item in the value list. Example usage:
def citiesLived = [
Alice: ['NY', 'LA'],
Bob: ['NY'],
Cara: ['LA', 'CHI']
]
def grouped = citiesLived.groupByMany()
assert grouped == [
NY : ['Alice', 'Bob'],
LA : ['Alice', 'Cara'],
CHI : ['Cara']
]
Groups all map entries into groups determined by the supplied mapping closure. The closure will be passed a Map.Entry or key and value (depending on the number of parameters the closure accepts) and should return the key that each item should be grouped under. The resulting map will have an entry for each 'group' key returned by the closure, with values being the list of map entries that belong to each group. (If instead of a list of map entries, you want an actual map use {code}groupBy{code}.)
def result = [a:1,b:2,c:3,d:4,e:5,f:6].groupEntriesBy { it.value % 2 }
assert result[0]*.key == ["b", "d", "f"]
assert result[1]*.value == [1, 3, 5]
closure - a 1 or 2 arg Closure mapping entries on keysIterates through the given map, passing in the initial value to the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value). The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until further iteration is not possible.
Also known as foldLeft or reduce in functional parlance. Examples:
def map = [a:1, b:2, c:3]
assert map.inject([]) { list, k, v ->
list + [k] * v
} == ['a', 'b', 'b', 'c', 'c', 'c']
initialValue - some initial valueclosure - a 2 or 3 arg ClosureIterates through the given map, passing in the initial value to the 2-arg Closure along with the first item (or 3-arg Closure along with the first key and value) and then similarly for other map entries. The results are collected in a list. Examples:
def map = [a:1, b:2, c:3]
assert map.injectAll('') { carry, k, v ->
carry + k * v
} == ['a', 'abb', 'abbccc']
initialValue - some initial valueclosure - a 2 or 3 arg ClosureCreate a Map composed of the intersection of both maps. Any entries that exist in both maps are added to the resultant map.
assert [4:4,5:5] == [1:1,2:2,3:3,4:4,5:5].intersect([4:4,5:5,6:6,7:7,8:8])
assert [1: 1, 2: 2, 3: 3, 4: 4].intersect( [1: 1.0, 2: 2, 5: 5] ) == [1:1, 2:2]
right - a mapSpecial 'case' implementation for maps which tests if the 'switch' operand exists in the key set. For example:
switch( 'foo' ) {
case [foo:true, bar:false]:
assert true
break
default:
assert false
}
switchValue - the switch value
Determines if the Map entries are sorted. Assumes the entries are comparable and uses a NumberAwareValueComparator to determine the order. The map's iteration order is checked.
def map = new LinkedHashMap([b:3, d:4, a:5, c:6])
assert map.isSorted()
Determines if the Map entries are sorted according to the given Comparator.
The map's iteration order is checked.
SortedMap instances always return true.
comparator - a Comparator used to compare Map.Entry instancesDetermines if the Map entries are sorted using the given Closure to determine order.
If the Closure has two parameters it is used like a traditional Comparator on entries. Otherwise, the Closure is assumed to take a single entry parameter and return a Comparable which is then used for further comparison.
condition - a Closure used as a comparatorReturns an Iterator for the given Map's entry set.
Overloads the left shift operator to provide an easy way to append Map.Entry values to a Map.
entry - a Map.Entry to be added to the Map. Overloads the left shift operator to provide an easy way to put
one maps entries into another map. This allows the compact syntax
map1 << map2; otherwise it's just a synonym for
putAll though it returns the original map rather than
being a void method. Example usage:
def map = [a:1, b:2]
map << [c:3, d:4]
assert map == [a:1, b:2, c:3, d:4]
other - another Map whose entries should be added to the original Map.Selects an entry in the map having the maximum calculated value as determined by the supplied closure. If more than one entry has the maximum value, an arbitrary choice is made between the entries having the maximum value.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison. An example:
def zoo = [monkeys:6, lions:5, tigers:7]
def mostCommonEntry = zoo.max{ it.value }
assert mostCommonEntry.value == 7
def leastCommonEntry = zoo.max{ a, b -> b.value <=> a.value } // double negative!
assert leastCommonEntry.value == 5
Edge case for multiple max values:
def zoo = [monkeys:6, lions:5, tigers:7]
def lengthOfNamePlusNumber = { e -> e.key.size() + e.value }
def ans = zoo.max(lengthOfNamePlusNumber) // one of [monkeys:6, tigers:7]
assert lengthOfNamePlusNumber(ans) == 13
closure - a 1 or 2 arg Closure used to determine the correct orderingSelects an entry in the map having the minimum calculated value as determined by the supplied closure. If more than one entry has the minimum value, an arbitrary choice is made between the entries having the minimum value.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single parameter and return a Comparable (typically an Integer) which is then used for further comparison.
def zoo = [monkeys:6, lions:5, tigers:7]
def leastCommonEntry = zoo.min{ it.value }
assert leastCommonEntry.value == 5
def mostCommonEntry = zoo.min{ a, b -> b.value <=> a.value } // double negative!
assert mostCommonEntry.value == 7
Edge case for multiple min values:
def zoo = [monkeys:6, lions:5, tigers:7]
def lastCharOfName = { e -> e.key[-1] }
def ans = zoo.min(lastCharOfName) // some random entry
assert lastCharOfName(ans) == 's'
closure - a 1 or 2 arg Closure used to determine the correct orderingCreate a Map composed of the entries of the first map minus the entries of the given map.
removeMe - the entries to exclude Returns a new Map containing all entries from left and right,
giving precedence to right. Any keys appearing in both Maps
will appear in the resultant map with values from the right
operand. If the left map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
Roughly equivalent to Map m = new HashMap(); m.putAll(left); m.putAll(right); return m;
but with some additional logic to preserve the left Map type for common cases as
described above.
assert [a:10, b:20] + [a:5, c:7] == [a:5, b:20, c:7]
right - a Map Returns a new Map containing all entries from self and entries,
giving precedence to entries. Any keys appearing in both Maps
will appear in the resultant map with values from the entries
operand. If self map is one of TreeMap, LinkedHashMap, Hashtable
or Properties, the returned Map will preserve that type, otherwise a HashMap will
be returned.
entries - a Collection of Map.Entry items to be added to the Map.Appends a String to the literal of the Map instance.
assert '[a:1] is a map' == [a:1] + ' is a map'
right - a StringAppends a GString to the literal of the Map instance.
assert '[a:1] is a map' == [a:1] + " is ${'a'} map"
right - a GStringProvides an easy way to append multiple Map.Entry values to a Map.
entries - a Collection of Map.Entry items to be added to the Map.A helper method to allow maps to work with subscript operators
key - an Object as a key for the mapvalue - the value to put into the map Modifies this map by removing the elements that are matched according to the
specified closure condition. If the closure takes one parameter then it will be
passed the Map.Entry. Otherwise the closure should take two parameters, which
will be the key and the value.
def map = [a:1, b:2]
map.removeAll { k,v -> k == 'b' }
assert map == [a:1]
See also findAll when wanting to produce a new map containing items
which match some criteria but leaving the original map unchanged.
condition - a 1 or 2 arg Closure condition applying on the entries Modifies this map so that it retains only its elements that are matched
according to the specified closure condition. In other words, removes from
this map all of its elements that don't match. If the closure takes one
parameter then it will be passed the Map.Entry. Otherwise the closure should
take two parameters, which will be the key and the value.
def map = [a:1, b:2]
map.retainAll { k,v -> k == 'b' }
assert map == [b:2]
See also findAll when wanting to produce a new map containing items
which match some criteria but leaving the original map unchanged.
condition - a 1 or 2 arg Closure condition applying on the entriesAllows a Map to be iterated through in reverse order using a closure. In general, the order in which the map contents are processed cannot be guaranteed. In practise, specialized forms of Map, e.g. a TreeMap will have its contents processed according to the reverse of the natural ordering of the map.
closure - the 1 or 2 arg closure applied on each entry of the mapSorts the elements from the given map into a new ordered map using the closure as a comparator to determine the ordering. The original map is unchanged.
def map = [a:5, b:3, c:6, d:4].sort { a, b -> a.value <=> b.value }
assert map == [b:3, d:4, a:5, c:6]
closure - a Closure used as a comparatorSorts the elements from the given map into a new ordered Map using the specified key comparator to determine the ordering. The original map is unchanged.
def map = [ba:3, cz:6, ab:5].sort({ a, b -> a[-1] <=> b[-1] } as Comparator)
assert map*.value == [3, 5, 6]
comparator - a ComparatorSorts the elements from the given map into a new ordered Map using the natural ordering of the keys to determine the ordering. The original map is unchanged.
map = [ba:3, cz:6, ab:5].sort()
assert map*.value == [5, 3, 6]
Synonym for Map.toSpreadMap.
Creates a sub-Map containing the given keys. This method is similar to List.subList() but uses keys rather than index ranges.
assert [1:10, 2:20, 4:40].subMap( [2, 4] ) == [2:20, 4:40]
keys - a Collection of keysCreates a sub-Map containing the given keys. This method is similar to List.subList() but uses keys rather than index ranges. The original map is unaltered.
def orig = [1:10, 2:20, 3:30, 4:40]
assert orig.subMap([1, 3] as int[]) == [1:10, 3:30]
assert orig.subMap([2, 4] as Integer[]) == [2:20, 4:40]
assert orig.size() == 4
keys - an array of keys Returns a new map containing the first num elements from the head of this map.
If the map instance does not have ordered keys, then this function could return a random num
entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
def strings = [ 'a':10, 'b':20, 'c':30 ]
assert strings.take( 0 ) == [:]
assert strings.take( 2 ) == [ 'a':10, 'b':20 ]
assert strings.take( 5 ) == [ 'a':10, 'b':20, 'c':30 ]
num - the number of elements to take from this mapnum elements of this map,
or else the whole map if it has less than num elements.Returns the longest prefix of this Map where each entry (or key/value pair) when passed to the given closure evaluates to true.
def shopping = [milk:1, bread:2, chocolate:3]
assert shopping.takeWhile{ it.key.size() < 6 } == [milk:1, bread:2]
assert shopping.takeWhile{ it.value % 2 } == [milk:1]
assert shopping.takeWhile{ k, v -> k.size() + v <= 7 } == [milk:1, bread:2]
If the map instance does not have ordered keys, then this function could appear to take random
entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
condition - a 1 (or 2) arg Closure that must evaluate to true for the
entry (or key and value) to continue taking elements Returns the string representation of this map. The string displays the
contents of the map, i.e. [one:1, two:2, three:3].
Returns the string representation of this map. The string displays the
contents of the map, i.e. [one:1, two:2, three:3].
maxSize - stop after approximately this many characters and append '...' Sorts the elements from the given map into a new ordered map using
a NumberAwareComparator on map entry values to determine the resulting order.
NumberAwareComparator has special treatment for numbers but otherwise uses the
natural ordering of the Iterator elements. The original map is unchanged.
def map = [a:5L, b:3, c:6, d:4.0].toSorted()
assert map.toString() == '[b:3, d:4.0, a:5, c:6]'
Sorts the elements from the given map into a new ordered map using the supplied comparator to determine the ordering. The original map is unchanged.
def keyComparator = [compare: { e1, e2 -> e1.key <=> e2.key }] as Comparator
def valueComparator = [compare: { e1, e2 -> e1.value <=> e2.value }] as Comparator
def map1 = [a:5, b:3, d:4, c:6].toSorted(keyComparator)
assert map1.toString() == '[a:5, b:3, c:6, d:4]'
def map2 = [a:5, b:3, d:4, c:6].toSorted(valueComparator)
assert map2.toString() == '[b:3, d:4, a:5, c:6]'
comparator - a Comparator used for the comparisonSorts the elements from the given map into a new ordered map using the supplied Closure condition as a comparator to determine the ordering. The original map is unchanged.
If the closure has two parameters it is used like a traditional Comparator. I.e. it should compare its two entry parameters for order, returning a negative integer, zero, or a positive integer when the first parameter is less than, equal to, or greater than the second respectively. Otherwise, the Closure is assumed to take a single entry parameter and return a Comparable (typically an Integer) which is then used for further comparison.
def map = [a:5, b:3, c:6, d:4].toSorted { a, b -> a.value <=> b.value }
assert map.toString() == '[b:3, d:4, a:5, c:6]'
condition - a Closure used as a comparator Returns a new SpreadMap from this map.
The example below shows the various possible use cases:
def fn(Map m) { return m.a + m.b + m.c + m.d }
assert fn(a:1, b:2, c:3, d:4) == 10
assert fn(a:1, *:[b:2, c:3], d:4) == 10
assert fn([a:1, b:2, c:3, d:4].toSpreadMap()) == 10
assert fn((['a', 1, 'b', 2, 'c', 3, 'd', 4] as Object[]).toSpreadMap()) == 10
assert fn(['a', 1, 'b', 2, 'c', 3, 'd', 4].toSpreadMap()) == 10
assert fn(['abcd'.toList(), 1..4].transpose().flatten().toSpreadMap()) == 10
Note that toSpreadMap() is not normally used explicitly but under the covers by Groovy.
Wraps a map using the decorator pattern with a wrapper that intercepts all calls
to get(key). If an unknown key is found, a default value will be
stored into the Map before being returned. The default value stored will be the
result of calling the supplied Closure with the key as the parameter to the Closure.
Example usage:
def map = [a:1, b:2].withDefault{ k -> k.toCharacter().isLowerCase() ? 10 : -10 }
def expected = [a:1, b:2, c:10, D:-10]
assert expected.every{ e -> e.value == map[e.key] }
def constMap = [:].withDefault{ 42 }
assert constMap.foo == 42
assert constMap.size() == 1
init - a Closure which is passed the unknown key Wraps a map using the decorator pattern with a wrapper that intercepts all calls
to get(key) and put(key, value).
If an unknown key is found for get, a default value will be returned.
The default value will be the result of calling the supplied Closure with the key
as the parameter to the Closure.
If autoGrow is set, the value will be stored into the map.
If autoShrink is set, then an attempt to put the default value
into the map is ignored and indeed any existing value would be removed.
If you wish the backing map to be as small as possible, consider setting autoGrow
to false and autoShrink to true.
This keeps the backing map as small as possible, i.e. sparse, but also means that
containsKey, keySet, size, and other methods
will only reflect the sparse values.
If you are wrapping an immutable map, you should set autoGrow
and autoShrink to false.
In this scenario, the get method is essentially a shorthand
for calling getOrDefault with the default value supplied once as a Closure.
Example usage:
// sparse map example
def answers = [life: 100].withDefault(false, true){ 42 }
assert answers.size() == 1
assert answers.foo == 42
assert answers.size() == 1
answers.life = 42
answers.putAll(universe: 42, everything: 42)
assert answers.size() == 0
// immutable map example
def certainties = [death: true, taxes: true].asImmutable().withDefault(false, false){ false }
assert certainties.size() == 2
assert certainties.wealth == false
assert certainties.size() == 2
autoGrow - whether calling get could potentially grow the map if the key isn't foundautoShrink - whether calling put with the default value could potentially shrink the mapinit - a Closure which is passed the unknown key