Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Collections and Closures

Groovy Maps

Learn Groovy maps: literal syntax, property and bracket access, default values with withDefault, iteration with each, entries, grouping, ordering, sorting and the GString key trap.

A map stores values under keys. Groovy gives maps their own literal syntax, lets you read and write entries with either dot or bracket notation, and adds methods to loop, filter, group and transform them. By default a Groovy map is a java.util.LinkedHashMap, which keeps insertion order.

Groovy blocks are read-only here, with Java stand-ins you can run.

Creating maps

GROOVY
def empty = [:]
def ages = [ada: 36, linus: 54, grace: 85]
def mixed = [name: 'Ada', langs: ['Groovy', 'Java'], address: [city: 'London']]
def numeric = [(1): 'one', (2): 'two']     // parentheses make the key an expression
println ages.class                         // class java.util.LinkedHashMap

Keys written as bare words (ada:) are strings, not variables. If you want a variable's value as a key, wrap it in parentheses:

GROOVY
def k = 'id'
def wrong = [k: 1]        // key is the string 'k'
def right = [(k): 1]      // key is 'id'

Other map types are one cast away: [b: 1, a: 2] as TreeMap (sorted), new HashMap() (unordered), new ConcurrentHashMap().

Reading and writing

GROOVY
def person = [name: 'Ada', age: 36]
println person.name          // Ada      (property style)
println person['age']        // 36       (bracket style)
println person.get('name')   // Ada      (Java style)
println person.missing       // null     (no exception)

person.city = 'London'       // add or replace
person['age'] = 37
person.remove('city')
println person               // [name:Ada, age:37]
println person.size()        // 2

Property-style access is shortest, but it fails for keys that clash with map properties (class, empty) or contain odd characters. In those cases use brackets: map['class']. Remember the GString trap from Strings and GStrings: map."$key" and map["$key"] work for reading and writing because Groovy converts the GString, but putting a GString key into a map literal creates a GString key.

Defaults

GROOVY
def counts = [:]
println counts.getOrDefault('x', 0)         // 0 (does not store)
counts.put('x', counts.get('x', 0) + 1)     // get(key, default) STORES the default
def lazy = [:].withDefault { 0 }
lazy.hits++                                 // starts from 0
lazy.hits++
println lazy                                // [hits:2]

withDefault is perfect for counters and for grouping lists:

GROOVY
def groups = [:].withDefault { [] }
groups.fruit << 'apple'
groups.fruit << 'pear'
groups.veg << 'kale'
println groups     // [fruit:[apple, pear], veg:[kale]]
Java Java stand-in: counting words with a default

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Iterating

The closure given to each receives either an entry or a key and a value:

GROOVY
def ages = [ada: 36, linus: 54]
ages.each { entry -> println "$entry.key is $entry.value" }
ages.each { name, age -> println "$name is $age" }
ages.eachWithIndex { name, age, i -> println "$i: $name" }
for (e in ages) { println e.key }
println ages.keySet()       // [ada, linus]
println ages.values()       // [36, 54]

Both closure forms work; the two-argument form is clearer when you need both parts.

Transforming and searching

GROOVY
def ages = [ada: 36, linus: 54, grace: 85]

println ages.findAll { k, v -> v > 40 }               // [linus:54, grace:85]
println ages.find { k, v -> v > 40 }                  // linus=54 (first entry)
println ages.collect { k, v -> "$k:$v" }              // [ada:36, linus:54, grace:85]
println ages.collectEntries { k, v -> [(k.toUpperCase()): v + 1] }
println ages.any { k, v -> v > 80 }                   // true
println ages.every { k, v -> v > 80 }                 // false
println ages.count { k, v -> v > 40 }                 // 2
println ages.max { it.value }.key                     // grace
println ages.sort { it.value }.keySet()               // [ada, linus, grace]
println ages.subMap(['ada', 'grace'])                 // [ada:36, grace:85]
println ages.values().sum()                           // 175

findAll on a map returns a map; collect returns a list; collectEntries returns a map, so use it to build a new map from an old one. find returns a Map.Entry.

Grouping and counting

GROOVY
def words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry']
println words.groupBy { it[0] }
// [a:[apple, avocado], b:[banana, blueberry], c:[cherry]]
println words.countBy { it.length() }
// [5:1, 7:1, 6:2, 9:1] (map of length to count)

groupBy and countBy are called on lists but produce maps, so they are the map-building tools you will use most.

Combining maps

GROOVY
def a = [x: 1, y: 2]
def b = [y: 20, z: 30]
println a + b                    // [x:1, y:20, z:30] (right side wins)
println a - [x: 1]               // [y:2]
a.putAll(b)                      // in place
println a.entrySet()*.key        // [x, y, z]
println a.subMap('x')            // [x:1]
println [x: 1].isEmpty()         // false
println a.containsKey('x')       // true
println a.containsValue(30)      // true

Spread works in map literals: [*:a, extra: 1] copies all entries of a first.

Nested maps and safe access

Nested maps pair well with the safe-navigation operator:

GROOVY
def config = [db: [host: 'localhost', port: 5432]]
println config.db.port            // 5432
println config.cache?.size        // null (cache is missing, no exception)

Maps like these are what JSON parsing returns, which is why working with parsed JSON in Groovy feels natural.

Ordering and sorting

LinkedHashMap remembers insertion order. Sort by key or value with sort, which returns a new map ordered accordingly:

GROOVY
def m = [b: 2, c: 3, a: 1]
println m.sort()                         // [a:1, b:2, c:3]  (by key)
println m.sort { -it.value }             // [c:3, b:2, a:1]  (by value, descending)
println (m as TreeMap)                   // [a:1, b:2, c:3]
Java Java stand-in: group words by first letter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Common mistakes

  • Using a bare word key when you meant a variable. Wrap it in parentheses.
  • Using a GString as a key in a literal.
  • Assuming map.each { it } receives only the value: with a single parameter you get the entry.
  • Forgetting that map.sort() and map.findAll return new maps.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In def m = [key: 1], what is the key?

    Bare words in a map literal are string keys. Use [(key): 1] to use a variable's value.
  2. 2. What does [a: 1].missing return?

    Reading an absent key with property syntax returns null.
  3. 3. Which method builds a NEW MAP from an existing map by transforming keys and values?

    collectEntries returns a map from closures that return [key, value] pairs. collect returns a list.
  4. 4. Which map type does a Groovy map literal create by default?

    LinkedHashMap keeps entries in insertion order.

Summary

  • Map literals use [key: value]; bare keys are strings, (expr) keys are evaluated.
  • Read and write with map.key, map['key'] or get; missing keys give null.
  • withDefault creates counters and grouping maps without checks.
  • findAll, collectEntries, groupBy, countBy, sort and subMap transform maps.
  • Avoid GString keys in map literals.

Next: Ranges and Sets