|
Groovy JDK |
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 collection, Closure closure)
Iterates through this Map transforming each entry into a new value using the closure as a transformer, returning a list of transformed values. |
List
|
collect(Closure closure)
Iterates through this Map transforming each entry into a new value using the closure as a transformer, returning a list of transformed values. |
Map
|
collectEntries(Map result, Closure closure)
Iterates through this Map transforming each entry using the closure as a transformer, returning a map of the transformed entries. |
Map
|
collectEntries(Closure closure)
Iterates through this Map transforming each entry using the closure as a transformer, returning a map of the transformed entries. |
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
|
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 by passing each map entry to the closure, otherwise it returns the defaultResult. |
Object
|
findResult(Closure closure)
Returns the first non-null closure result by passing each map entry to the closure. |
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
|
groupEntriesBy(Closure closure)
Groups all map entries into groups determined by the supplied mapping closure. |
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 operands)
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. |
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 delegate pattern with a wrapper that intercepts all calls to get(key) .
|
Method Detail |
---|
public boolean any(Closure closure)
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 }
closure
- the 1 or 2 arg closure predicate used for matching.public boolean asBoolean()
assert [:] as Boolean == false assert [a:2] as Boolean == true
public Map asImmutable()
public Map asSynchronized()
public Object asType(Class clazz)
clazz
- the target type.public Collection collect(Collection collection, Closure closure)
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
collection
- the Collection to which the mapped values are added.closure
- the closure used for mapping, which can take one (Map.Entry) or two (key, value) parameters.public List collect(Closure closure)
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]
closure
- the closure used to map each element of the collection.public Map collectEntries(Map result, Closure closure)
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']
result
- the Map into which the mapped entries are put.closure
- the closure used for mapping, 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.public Map collectEntries(Closure closure)
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']
closure
- the closure used for mapping, 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.public Number count(Closure closure)
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 entries.public Map countBy(Closure closure)
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 keys.public Map each(Closure closure)
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 map.public Map eachWithIndex(Closure closure)
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 item.public boolean equals(Map other)
Example usage:
assert [a:2, b:3] == [a:2L, b:3.0]
other
- the Map being compared to.public boolean every(Closure closure)
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 }
closure
- the 1 or 2 arg Closure predicate used for matching.public Entry find(Closure closure)
assert [a:1, b:3].find { it.value == 3 }.key == "b"
closure
- a 1 or 2 arg Closure condition.public Map findAll(Closure closure)
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 entries.public Object findResult(Object defaultResult, Closure closure)
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}" }
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.public Object findResult(Closure closure)
assert "Found b:3" == [a:1, b:3].findResult { if (it.value == 3) return "Found ${it.key}:${it.value}" }
closure
- a 1 or 2 arg Closure that returns a non-null value when processing should stop and a value should be returned.public Object get(Object key, Object defaultValue)
def map=[:] map.get("a", []) << 5 assert map == [a:[5]]
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.public Object getAt(Object key)
def map = [a:10] assert map["a"] == 10
key
- an Object as a key for the map.public Map groupBy(Closure closure)
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.public Map groupEntriesBy(Closure closure)
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 keys.public Map intersect(Map right)
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 map.public boolean isCase(Object switchValue)
switch( 'foo' ) { case [foo:true, bar:false]: assert true break default: assert false }
switchValue
- the switch value.public Map leftShift(Entry entry)
entry
- a Map.Entry to be added to the Map..public Map leftShift(Map other)
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..public Entry max(Closure closure)
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 == 5Edge 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 ordering.public Entry min(Closure closure)
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 == 7Edge 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 ordering.public Map minus(Map operands)
operands
- the entries to remove from the map.public Map plus(Map right)
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.public Map plus(Collection entries)
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..public Map putAll(Collection entries)
entries
- a Collection of Map.Entry items to be added to the Map..public Object putAt(Object key, Object value)
key
- an Object as a key for the map.value
- the value to put into the map.public Map reverseEach(Closure closure)
closure
- the 1 or 2 arg closure applied on each entry of the map.public Map sort(Closure closure)
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 comparator.public Map sort(Comparator comparator)
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 Comparator.public Map sort()
map = [ba:3, cz:6, ab:5].sort() assert map*.value == [5, 3, 6]
public SpreadMap spread()
public Map subMap(Collection keys)
assert [1:10, 2:20, 4:40].subMap( [2, 4] ) == [2:20, 4:40]
keys
- a Collection of keys.public String toMapString()
[one:1, two:2, three:3]
.public String toMapString(int maxSize)
[one:1, two:2, three:3]
.maxSize
- stop after approximately this many characters and append '...'.public SpreadMap toSpreadMap()
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()) == 10Note that toSpreadMap() is not normally used explicitly but under the covers by Groovy.
public Map withDefault(Closure init)
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.
|
Groovy JDK |