Groovy map (dictionary, hash, associative array)

Groovy map access elements

g = [:]       // create map
println(g)

g['name'] = []   // create array
println(g)

g['name'].add("foo")
g['name'].add("bar")
println(g)
def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']
println colors
println colors.containsKey('red')
println colors.containsKey('black')

for (p in colors) {
    println p.key
    println p.value
}

Get all the keys ina Groovy map

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']

for (key in colors.keySet()) {
    println(key)
    println(colors[key])
}
red
#FF0000
green
#00FF00
blue
#0000FF

Sorted keys of a Groovy map

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']

for (key in colors.keySet().sort()) {
    println(key)
    println(colors[key])
}

Values of a Groovy map

def colors = [red: '#FF0000', green: '#00FF00', blue: '#0000FF']

for (key in colors.keySet().sort()) {
    println(key)
    println(colors[key])
}

Return map from a function

def f() {
  return ["a": 2, "b": 3]
}

r = f()
println r['a']
println r['b']

See also maps

timestamp: 2018-07-31T22:30:01 tags:

  • map
  • containsKey
  • key
  • value
  • keySet
  • values