Grails Cookbook - A collection of tutorials and examples

Groovy Add To Map Examples

Maps are very useful in programming. It can be used to cache results of expensive operations to help improve performance. One of the basic operation in maps is how to add entries to it. Below are some examples on how to Add or put values to a map in Groovy.

Groovy Add To Map

Here is an example map declaration with initial values
def personAgeMap = [matthew: 30, mark:25, luke: 40]

Since Groovy is just a superset of Java, we can use the put method to add an entry to a map.

personAgeMap.put('john', 41)

We can also use a syntax similar to accessing an array. For example:

personAgeMap['Tim'] = 28

Another way is to treat the key as property of the map object. Example:

personAgeMap.Roy = 32

You can also use dot (.) followed by the key enclosed in quotes. Example:

personAgeMap.'Tim' = 55

Lastly, you can add entries coming from another map. You can push entries from one map to another, for example:

personAgeMap << [Michael:29]

In summary, above are 5 ways of how to push an item in Groovy and add it to a map. There could be more ways in future version of Groovy.