Maps

A map literal is [key: value] and the object is a LinkedHashMap, which keeps the order the keys were written in. A key that is not an identifier needs the explicit form [(expr): value].

Keys and values

maps.groovy

def capitals = [france: 'Paris', japan: 'Tokyo', norway: 'Oslo'] println capitals.france println capitals['japan'] println capitals.get('spain', 'unknown') println capitals.containsKey('norway') println capitals.size() println capitals.keySet().sort() println capitals.values().sort()

groovy maps.groovy

Paris
Tokyo
unknown
true
4
[france, japan, norway, spain]
[Oslo, Paris, Tokyo, unknown]

map.key and map['key'] read the same entry; the dot is shorter and the brackets take a key that is computed. A missing key from get returns the second argument, while a missing key from [] returns null.

Writing and removing

maps.groovy

def ages = [ada: 36, grace: 85] ages.linus = 54 ages['barbara'] = 75 ages.remove('grace') println ages println ages.sort() println ages.findAll { String name, int age -> age < 60 }

groovy maps.groovy

[ada:36, linus:54, barbara:75]
[ada:36, barbara:75, linus:54]
[ada:36, linus:54]

An assignment to a missing property adds the entry, so a map behaves like a small record. sort() returns a new map ordered by key, which is how a map is printed the same way on every run.

Iterating a map

iterate.groovy

def ages = [ada: 36, grace: 85, linus: 54] ages.each { String name, int age -> println "${name}: ${age}" } for (entry in ages.entrySet()) { println "${entry.key} -> ${entry.value}" } println ages.collect { String name, int age -> "${name}=${age}" }.sort()

groovy iterate.groovy

ada: 36
grace: 85
linus: 54
ada -> 36
grace -> 85
linus -> 54
[ada=36, grace=85, linus=54]

A two-parameter closure on a map gets the key and the value; a one-parameter closure gets a Map.Entry. The order is the insertion order until something sorts it.

Related

Article author: Arthur Isaev

Banner image