Groovy JDK

java.util
Class Map

Method Summary
boolean any(Closure closure)
Iterates over the entries of a map, and checks whether a predicate is valid for at least one entry.
boolean asBoolean()
Coerce a map instance to a boolean value.
Map asImmutable()
A convenience method for creating an immutable map.
Map asSynchronized()
A convenience method for creating a synchronized Map.
Object asType(Class clazz)
Coerces this map to the given type, using the map's keys as the public method names, and values as the implementation.
Collection collect(Collection collector, Closure 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.
List collect(Closure transform)
Iterates through this Map transforming each map entry into a new value using the transform closure returning a list of transformed values.
Map collectEntries(Map collector, Closure transform)
Iterates through this Map transforming each map entry using the transform closure returning a map of the transformed entries.
Map collectEntries(Closure transform)
Iterates through this Map transforming each entry using the transform closure and returning a map of the transformed entries.
Collection collectMany(Collection collector, Closure projection)
Projects each item from a source map to a result collection and concatenates (flattens) the resulting collections adding them into the collector.
Collection collectMany(Closure projection)
Projects each item from a source map to a result collection and concatenates (flattens) the resulting collections adding them into a collection.
Number count(Closure closure)
Counts the number of occurrences which satisfy the given closure from inside this map.
Map countBy(Closure closure)
Groups the members of a map into groups determined by the supplied mapping closure and counts the frequency of the created groups.
Map drop(int num)
Drops the given number of key/value pairs from the head of this map if they are available.
Map 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).
Map each(Closure closure)
Allows a Map to be iterated through using a closure.
Map eachWithIndex(Closure closure)
Allows a Map to be iterated through using a closure.
boolean equals(Map other)
Compares two Maps treating coerced numerical values as identical.
boolean every(Closure closure)
Iterates over the entries of a map, and checks whether a predicate is valid for all entries.
Entry find(Closure closure)
Finds the first entry matching the closure condition.
Map findAll(Closure closure)
Finds all entries matching the closure condition.
Object findResult(Object defaultResult, Closure closure)
Returns the first non-null closure result found by passing each map entry to the closure, otherwise the defaultResult is returned.
Object findResult(Closure closure)
Returns the first non-null closure result found by passing each map entry to the closure, otherwise null is returned.
Collection findResults(Closure filteringTransform)
Iterates through the map transforming items using the supplied closure and collecting any non-null results.
Object get(Object key, Object defaultValue)
Looks up an item in a Map for the given key and returns the value - unless there is no entry for the given key in which case add the default value to the map and return that.
Object getAt(Object key)
Support the subscript operator for a Map.
Map groupBy(Closure closure)
Groups the members of a map into sub maps determined by the supplied mapping closure.
Map groupBy(Object closures)
Groups the members of a map into sub maps determined by the supplied mapping closures.
Map groupBy(List closures)
Groups the members of a map into sub maps determined by the supplied mapping closures.
Map groupEntriesBy(Closure closure)
Groups all map entries into groups determined by the supplied mapping closure.
Object inject(Object initialValue, Closure 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).
Map intersect(Map right)
Create a Map composed of the intersection of both maps.
boolean isCase(Object switchValue)
'Case' implementation for maps which tests the groovy truth value obtained using the 'switch' operand as key.
Map leftShift(Entry entry)
Overloads the left shift operator to provide an easy way to append Map.Entry values to a Map.
Map leftShift(Map other)
Overloads the left shift operator to provide an easy way to put one maps entries into another map.
Entry max(Closure closure)
Selects an entry in the map having the maximum calculated value as determined by the supplied closure.
Entry min(Closure closure)
Selects an entry in the map having the minimum calculated value as determined by the supplied closure.
Map minus(Map removeMe)
Create a Map composed of the entries of the first map minus the entries of the given map.
Map plus(Map right)
Returns a new Map containing all entries from left and right, giving precedence to right.
Map plus(Collection entries)
Returns a new Map containing all entries from self and entries, giving precedence to entries.
Map putAll(Collection entries)
Provides an easy way to append multiple Map.Entry values to a Map.
Object putAt(Object key, Object value)
A helper method to allow maps to work with subscript operators
Map reverseEach(Closure closure)
Allows a Map to be iterated through in reverse order using a closure.
Map 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.
Map sort(Comparator comparator)
Sorts the elements from the given map into a new ordered Map using the specified key comparator to determine the ordering.
Map sort()
Sorts the elements from the given map into a new ordered Map using the natural ordering of the keys to determine the ordering.
SpreadMap spread()
Synonym for Map#toSpreadMap.
Map subMap(Collection keys)
Creates a sub-Map containing the given keys.
Map subMap(K[] keys)
Creates a sub-Map containing the given keys.
Map take(int num)
Returns a new map containing the first num elements from the head of this map.
Map 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.
String toMapString()
Returns the string representation of this map.
String toMapString(int maxSize)
Returns the string representation of this map.
SpreadMap toSpreadMap()
Returns a new SpreadMap from this map.
Map withDefault(Closure init)
Wraps a map using the decorator pattern with a wrapper that intercepts all calls to get(key).
 
Method Detail

any

public boolean any(Closure closure)
 
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 }
Parameters:
closure - the 1 or 2 arg closure predicate used for matching.
Returns:
true if any entry in the map matches the closure predicate
Since:
1.5.0

asBoolean

public boolean asBoolean()
 
Coerce 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
Returns:
the boolean value
Since:
1.7.0

asImmutable

public Map asImmutable()
 
A convenience method for creating an immutable map.
Returns:
an immutable Map
Since:
1.0
See:
Collections#unmodifiableMap.

asSynchronized

public Map asSynchronized()
 
A convenience method for creating a synchronized Map.
Returns:
a synchronized Map
Since:
1.0
See:
Collections#synchronizedMap.

asType

public Object asType(Class clazz)
 
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.
Parameters:
clazz - the target type.
Returns:
a Proxy of the given type, which defers calls to this map's elements.
Since:
1.0

collect

public Collection collect(Collection collector, Closure 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.
assert [a:1, b:2].collect( [] as HashSet ) { key, value -> key*value } == ["a", "bb"] as Set
assert [3:20, 2:30].collect( [] as HashSet ) { entry -> entry.key * entry.value } == [60] as Set
Parameters:
collector - the Collection to which transformed values are added.
transform - the transformation closure which can take one (Map.Entry) or two (key, value) parameters.
Returns:
the collector with all transformed values added to it
Since:
1.0

collect

public List collect(Closure transform)
 
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]
Parameters:
transform - the transformation closure which can take one (Map.Entry) or two (key, value) parameters.
Returns:
the resultant list of transformed values
Since:
1.0

collectEntries

public Map collectEntries(Map collector, Closure transform)
 
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 -> [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']
Parameters:
collector - the Map into which the transformed entries are put.
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 value.
Returns:
the collector with all transformed values added to it
Since:
1.7.9
See:
Map#collect(Collection, Closure).

collectEntries

public Map collectEntries(Closure transform)
 
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']
Parameters:
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 value.
Returns:
a Map of the transformed entries
Since:
1.7.9
See:
Map#collect(Collection, Closure).

collectMany

public Collection collectMany(Collection collector, Closure projection)
 
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 -> k.startsWith('b') ? k.toList() : [] }
assert result == ['x', 'b', 'r', 'e', 'a', 'd', 'b', 'u', 't', 't', 'e', 'r']
Parameters:
collector - an initial collection to add the projected items to.
projection - a projecting Closure returning a collection of items.
Returns:
the collector with the projected collections concatenated (flattened) to it
Since:
1.8.8

collectMany

public Collection collectMany(Closure projection)
 
Projects 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']
Parameters:
projection - a projecting Closure returning a collection of items.
Returns:
the collector with the projected collections concatenated (flattened) to it
Since:
1.8.8

count

public Number count(Closure closure)
 
Counts 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
Parameters:
closure - a 1 or 2 arg Closure condition applying on the entries.
Returns:
the number of occurrences
Since:
1.8.0

countBy

public Map countBy(Closure closure)
 
Groups 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]
Parameters:
closure - a closure mapping entries to frequency count keys.
Returns:
a new Map grouped by keys with frequency counts
Since:
1.8.0

drop

public Map drop(int num)
 
Drops 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.
Parameters:
num - the number of elements to drop from this map.
Returns:
a map consisting of all key/value pairs of this map except the first num ones, or else the empty map, if this map has less than num elements.
Since:
1.8.1

dropWhile

public Map 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).
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 drop random entries. Groovy by default uses LinkedHashMap, so this shouldn't be an issue in the main.
Parameters:
condition - a 1 (or 2) arg Closure that must evaluate to true for the entry (or key and value) to continue dropping elements.
Returns:
the shortest suffix of the given Map such that the given closure condition evaluates to true for each element dropped from the front of the Map
Since:
1.8.7

each

public Map each(Closure closure)
 
Allows 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.
Parameters:
closure - the 1 or 2 arg closure applied on each entry of the map.
Returns:
returns the self parameter
Since:
1.5.0

eachWithIndex

public Map eachWithIndex(Closure closure)
 
Allows 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)"
Parameters:
closure - a 2 or 3 arg Closure to operate on each item.
Returns:
the self Object
Since:
1.5.0

equals

public boolean equals(Map other)
 
Compares two Maps treating coerced numerical values as identical.

Example usage:

assert [a:2, b:3] == [a:2L, b:3.0]
Parameters:
other - the Map being compared to.
Returns:
true if the contents of both maps are identical
Since:
1.8.0

every

public boolean every(Closure closure)
 
Iterates 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 }
Parameters:
closure - the 1 or 2 arg Closure predicate used for matching.
Returns:
true if every entry of the map matches the closure predicate
Since:
1.5.0

find

public Entry find(Closure closure)
 
Finds 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"
Parameters:
closure - a 1 or 2 arg Closure condition.
Returns:
the first Object found
Since:
1.0

findAll

public Map findAll(Closure closure)
 
Finds 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]
Parameters:
closure - a 1 or 2 arg Closure condition applying on the entries.
Returns:
a new subMap
Since:
1.0

findResult

public Object findResult(Object defaultResult, Closure closure)
 
Returns 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" }
Parameters:
defaultResult - an Object that should be returned if all closure results are null.
closure - a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned.
Returns:
the first non-null result collected by calling the closure, or the defaultResult if no such result was found
Since:
1.7.5

findResult

public Object findResult(Closure closure)
 
Returns 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" }
Parameters:
closure - a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned.
Returns:
the first non-null result collected by calling the closure, or null if no such result was found
Since:
1.7.5

findResults

public Collection findResults(Closure filteringTransform)
 
Iterates 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"]
Parameters:
filteringTransform - a 1 or 2 arg Closure that should return either a non-null transformed value or null for items which should be discarded.
Returns:
the list of non-null transformed values
Since:
1.8.1

get

public Object get(Object key, Object defaultValue)
 
Looks up an item in a Map for the given key and returns the value - unless there is no entry for the given key in which case add the default value to the map and return that.
def map=[:]
map.get("a", []) << 5
assert map == [a:[5]]
Parameters:
key - the key to lookup the value of.
defaultValue - the value to return and add to the map for this key if there is no entry for the given key.
Returns:
the value of the given key or the default value, added to the map if the key did not exist
Since:
1.0

getAt

public Object getAt(Object key)
 
Support the subscript operator for a Map.
def map = [a:10]
assert map["a"] == 10
Parameters:
key - an Object as a key for the map.
Returns:
the value corresponding to the given key
Since:
1.0

groupBy

public Map groupBy(Closure closure)
 
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]]
Parameters:
closure - a closure mapping entries on keys.
Returns:
a new Map grouped by keys
Since:
1.0

groupBy

public Map groupBy(Object closures)
 
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.
Parameters:
closures - an array of closures that map entries on keys.
Returns:
a new map grouped by keys on each criterion
Since:
1.8.1
See:
Closure#IDENTITY.

groupBy

public Map groupBy(List closures)
 
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.
Parameters:
closures - a list of closures that map entries on keys.
Returns:
a new map grouped by keys on each criterion
Since:
1.8.1
See:
Closure#IDENTITY.

groupEntriesBy

public Map groupEntriesBy(Closure closure)
 
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]
Parameters:
closure - a 1 or 2 arg Closure mapping entries on keys.
Returns:
a new Map grouped by keys
Since:
1.5.2

inject

public Object inject(Object initialValue, Closure 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). 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 the entire collection has been used. 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']
Parameters:
initialValue - some initial value.
closure - a 2 or 3 arg Closure.
Returns:
the result of the last closure call
Since:
1.8.1

intersect

public Map intersect(Map right)
 
Create 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]
Parameters:
right - a map.
Returns:
a Map as an intersection of both maps
Since:
1.7.4

isCase

public boolean isCase(Object switchValue)
 
'Case' implementation for maps which tests the groovy truth value obtained using the 'switch' operand as key. For example:
switch( 'foo' ) {
  case [foo:true, bar:false]:
    assert true
    break
  default:
    assert false
}
Parameters:
switchValue - the switch value.
Returns:
the groovy truth value from caseValue corresponding to the switchValue key
Since:
1.7.6

leftShift

public Map leftShift(Entry entry)
 
Overloads the left shift operator to provide an easy way to append Map.Entry values to a Map.
Parameters:
entry - a Map.Entry to be added to the Map..
Returns:
same map, after the value has been added to it.
Since:
1.6.0

leftShift

public Map leftShift(Map other)
 
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]
Parameters:
other - another Map whose entries should be added to the original Map..
Returns:
same map, after the values have been added to it.
Since:
1.7.2

max

public Entry max(Closure closure)
 
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
Parameters:
closure - a 1 or 2 arg Closure used to determine the correct ordering.
Returns:
the Map.Entry having the maximum value as determined by the closure
Since:
1.7.6

min

public Entry min(Closure closure)
 
Selects 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'
Parameters:
closure - a 1 or 2 arg Closure used to determine the correct ordering.
Returns:
the Map.Entry having the minimum value as determined by the closure
Since:
1.7.6

minus

public Map minus(Map removeMe)
 
Create a Map composed of the entries of the first map minus the entries of the given map.
Parameters:
removeMe - the entries to remove from the map.
Returns:
the resulting map
Since:
1.7.4

plus

public Map plus(Map right)
 
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]
Parameters:
right - a Map.
Returns:
a new Map containing all entries from left and right
Since:
1.5.0

plus

public Map plus(Collection entries)
 
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.
Parameters:
entries - a Collection of Map.Entry items to be added to the Map..
Returns:
a new Map containing all key, value pairs from self and entries
Since:
1.6.1

putAll

public Map putAll(Collection entries)
 
Provides an easy way to append multiple Map.Entry values to a Map.
Parameters:
entries - a Collection of Map.Entry items to be added to the Map..
Returns:
the same map, after the items have been added to it.
Since:
1.6.1

putAt

public Object putAt(Object key, Object value)
 
A helper method to allow maps to work with subscript operators
Parameters:
key - an Object as a key for the map.
value - the value to put into the map.
Returns:
the value corresponding to the given key
Since:
1.0

reverseEach

public Map reverseEach(Closure closure)
 
Allows 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.
Parameters:
closure - the 1 or 2 arg closure applied on each entry of the map.
Returns:
returns the self parameter
Since:
1.7.2
See:
Map#each(Closure).

sort

public Map 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. 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]
Parameters:
closure - a Closure used as a comparator.
Returns:
the sorted map
Since:
1.6.0

sort

public Map sort(Comparator comparator)
 
Sorts 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]
Parameters:
comparator - a Comparator.
Returns:
the sorted map
Since:
1.7.2

sort

public Map sort()
 
Sorts 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]
Returns:
the sorted map
Since:
1.7.2

spread

public SpreadMap spread()
 
Synonym for Map#toSpreadMap.
Returns:
a newly created SpreadMap
Since:
1.0

subMap

public Map subMap(Collection keys)
 
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]
Parameters:
keys - a Collection of keys.
Returns:
a new Map containing the given keys
Since:
1.0

subMap

public Map subMap(K[] keys)
 
Creates 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
Parameters:
keys - an array of keys.
Returns:
a new Map containing the given keys
Since:
2.1.0

take

public Map take(int num)
 
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 ]
Parameters:
num - the number of elements to take from this map.
Returns:
a new map consisting of the first num elements of this map, or else the whole map if it has less then num elements.
Since:
1.8.1

takeWhile

public Map 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.
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.
Parameters:
condition - a 1 (or 2) arg Closure that must evaluate to true for the entry (or key and value) to continue taking elements.
Returns:
a prefix of the given Map where each entry (or key/value pair) passed to the given closure evaluates to true
Since:
1.8.7

toMapString

public String toMapString()
 
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
Since:
1.0

toMapString

public String toMapString(int maxSize)
 
Returns the string representation of this map. The string displays the contents of the map, i.e. [one:1, two:2, three:3].
Parameters:
maxSize - stop after approximately this many characters and append '...'.
Returns:
the string representation
Since:
1.0

toSpreadMap

public SpreadMap toSpreadMap()
 
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.
Returns:
a newly created SpreadMap if this map is not null and its size is positive.
Since:
1.0
See:
SpreadMap#SpreadMap.

withDefault

public Map withDefault(Closure init)
 
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
Parameters:
init - a Closure which is passed the unknown key.
Returns:
the wrapped Map
Since:
1.7.1

Groovy JDK