Last editor: Dave Cherry, last modified: Aug 22, 2009
Probably the most basic case for iteration is to perform an operation on each element of a collection. In groovy this is performed using each. Each can be applied to many types, here we will consider a Map, as we saw a list example on the previous page.
def addressByName = [ 'dave' : 'some address', 'joe' : 'another address']
addressByName.each { key, value ->
println "${key} ${value}"
}
Notice in the above example that the closure take two parameters; which are the key and value of each entry in the map.
Sometimes all items in a collection need to be joined together, for example a list of names that is comma separated. Groovy provides join for this:
def nameList = ['dave', 'joe', 'fred']
println "${nameList.join(',')}"
The last case this article considers creating another collection from the existing one. In groovy this is done using collect.
def nameList = ['dave', 'joe', 'fred']
def outputList = nameList.collect {
n ->
"name is ${n}"
}
outputList.each {n -> println n}
Well that ends the whirlwind tour of groovy. I hope that this article has given you a good insight into this promising language. Don't forget that this article has only scratched the surface of whats available with groovy, take a look at some of our more indepth articles or get a good groovy book to delve deeper.