APPENDIX B: Introduction to Groovy 411
On line 1, an empty list is created by assigning a property the value of [].
Lines 2 to 4 create a list with an item already in it and add items to the list.
Line 5 iterates over the list, invoking the closure to print out the contents. The
each() method provides the ability to iterate over all elements in the list, invoking
the closure on each element.
Lines 6 illustrates how to use an index to access a list. Lists are zero-based.
Line 7 shows how to use an index to assign position 0 the value "Vishal".
Line 8 accesses the list using the get() method.
A
B
C
A
Vishal
Vishal
B
Maps
A Groovy map is an unordered collection of key-value pairs, where the key is unique, just as in
Java. It is an implementation of java.util.Map. Listing B-19 illustrates how to create maps and
common usages.
Listing B-19. Creating and Using Maps
- def map = ['a':'Value A', 'b':'Value B ']
- println map["a"]
- println map."a"
- println map.a
- println map.getAt("b")
- println map.get("b")
- println map.get("c", "unknown")
- println map
- map.d = "Value D"
- println map.d
- map.put('e', 'Value E')
- println map.e
- map.putAt 'f', 'Value F'
- println map.f
- map.each { println "Key: ${it.key}, Value: ${it.value}" }
- map.values().each { println it }