Groovy : Map

Groovy has a very bad documentation, but it's also so powerfull.

Play with Map

def empty = [:]
assert empty.size() == 0
 
//keys are Strings by default
assert [key:'value'] == ['key':'value']
 
//you must use parentheses if a variable should become a key
def myVar = "theKey"
def myMap = [(myVar):'someValue']
assert myMap['theKey'] == 'someValue'
 
//you can use array-style notation or bean-style notation to access and set entries
def map = [:]
//array-style
map['a'] = 1
assert map['a'] == 1
 
//bean-style
map.b = 2
assert map.b == 2
 
//using a default value in case the key is not available
def someMap = [a:1,b:2]
assert someMap.get('a', -1) == 1
assert someMap.get('c', -1) == -1
assert someMap.get('c') == -1 //TAKE CARE!
assert someMap.get('d') == null
 
//iterating over a map with each() -> "it" is an entry with properties key and value
def iterationMap = [a:1,b:2,c:3]
def keyList = []
iterationMap.each { keyList << it.key }
assert keyList.contains('a')
assert keyList.contains('b')
assert keyList.contains('c')
 
//or split the entry into key and value directly
iterationMap.each { key, value -> keyList << key}
assert keyList.size() == 6
 
//get all keys of a map
def keys = [a:1].keySet()
assert keys.size() == 1
assert keys.contains('a')
assert ['a'] as Set == [a:1].keySet()
assert ['a'] == [a:1].keySet().toList()
 
//you can use findAll with maps, too
def books = [	'Graeme Rocher':'The Definitive Guide to Grails',
		'Dierk Koenig':'Groovy in Action']
def subMap = books.findAll { key, value -> key == 'Graeme Rocher'}
assert subMap.size() == 1
assert subMap.'Graeme Rocher' == 'The Definitive Guide to Grails'
 
//and collect... collect does a transformation with each entry
def list = books.collect { key, value -> (key == 'Dierk Koenig')? 'GINA' : value }
assert list.join(',') == 'GINA,The Definitive Guide to Grails'

source: http://snipplr.com/view.php?codeview&id=2199