Working with Maps in Groovy


Groovy comes with native support for Maps.

Creating Map

def colourVsCode = ['red' : '#FF0000', 'green' : '#008000', 'blue' : '0000ff']

This is the simple way of creating a Map in groovy, The above code creates a Map of type java.util.LinkedHashMap

You can create an empty Map with following code

def colourVsCode = [:] // Creates an empty Map

Adding Elements to Map

Following are the different ways of adding elements to a Map

def colourVsCode = [:] // Creates an empty Map
		
colourVsCode.red = '#FF0000' // do not use this if your key is not a legal identifier ex. 'foo-bar'
colourVsCode['green'] = '#008000'

Reading Elements

Following are the different ways of reading elements from a Map

def colourVsCode = ['red' : '#FF0000', 'green' : '#008000', 'blue' : '0000ff']

colourVsCode.red // returns #FF0000
colourVsCode['green'] // returns #008000

Iterating on Map

Following are the four different ways of iterating on a Map

def colourVsCode = ['red' : '#FF0000', 'green' : '#008000', 'blue' : '0000ff']

println 'using each & entry'
colourVsCode.each{ entry ->
	println 'Key:' + entry.key + ', Value:' + entry.value
}

println '\nusing eachWithIndex & entry'
colourVsCode.eachWithIndex{ entry, i ->
	println 'Index:' + i + ', Key:' + entry.key + ', Value:' + entry.value
}

println '\nusing each & key, value'
colourVsCode.each{ key, value ->
	println 'Key:' + key + ', Value:' + value
}

println '\nusing eachWithIndex & key, value'
colourVsCode.eachWithIndex{ key, value, i ->
	println 'Key:' + key + ', Value:' + value
}

Output:

using each & entry
Key:red, Value:#FF0000
Key:green, Value:#008000
Key:blue, Value:0000ff

using eachWithIndex & entry
Index:0, Key:red, Value:#FF0000
Index:1, Key:green, Value:#008000
Index:2, Key:blue, Value:0000ff

using each & key, value
Key:red, Value:#FF0000
Key:green, Value:#008000
Key:blue, Value:0000ff

using eachWithIndex & key, value
Key:red, Value:#FF0000
Key:green, Value:#008000
Key:blue, Value:0000ff

Searching on Maps

You can use find & findAll to search on Maps, find returns the first occurrence where as findAll gives a list with all elements which pass the criteria

def employees = [
	1 : [name : 'name1', age: 25, gender: 'M'],
	2 : [name : 'name2', age: 21, gender: 'F'],
	3 : [name : 'name3', age: 28, gender: 'M'],
	4 : [name : 'name4', age: 35, gender: 'F'],
	5 : [name : 'name5', age: 22, gender: 'F']
]

def firstFemaleEmployee = employees.find { it.value.gender == 'F'}
println 'firstFemaleEmployee:' + firstFemaleEmployee

def allFemaleEmployees = employees.findAll { it.value.gender == 'F' }
println 'allFemaleEmployees:' + allFemaleEmployees

Output:

firstFemaleEmployee:2={name=name2, age=21, gender=F}
allFemaleEmployees:[2:[name:name2, age:21, gender:F], 4:[name:name4, age:35, gender:F], 5:[name:name5, age:22, gender:F]]