Java Reference
In-Depth Information
def both = ALEast + ALCentral
assert 5 == both.size()
Like Java maps, you can extract the set of keys from a map using the keySet method:
assert ALEast.keySet() == ['Boston','New York'] as Set
Mapsalsohavearathercontroversialmethodthatletsyouaddanewelementwithadefault
in case the element doesn't exist:
assert 'Blue Jays' == ALEast.get('Toronto','Blue Jays')
assert 'Blue Jays' == ALEast['Toronto']
Here I'm trying to retrieve a value using a key that isn't in the map ( Toronto ). If the key
exists, its value is returned. If not, it's added to the map, with the second argument to the
get method being its new value. This is convenient, but it means that if you accidentally
misspell a key when trying to retrieve it you don't get an error; instead, you wind up adding
it. That's not true when using the single-argument version of get .
Finally, when you iterate over a map using a closure, the number of dummy arguments de-
termines how the map is accessed. Using two arguments means that the map is accessed as
keys and values:
String keys1 = ''
List<Integer> values1 = []
both. each { key,val ->
keys1 += '|' + key
values1 << val
}
The each iterator has two dummy variables, so the first represents the key and the second
the value. This closure appends the keys to a string, separated by vertical bars. The values
are added to a list.
Alternatively, using a single argument assigns each entry to the specified argument, or it
if none:
String keys2 = ''
List<Integer> values2 = []
both. each { entry ->
keys2 += '|' + entry.key
Search WWH ::




Custom Search