blog rss feed

Getting groovy - an introduction to the Groovy language

Keywords:

Last editor: Dave Cherry, last modified: Aug 22, 2009

Iterating over each entry in a collection

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.

Joining all the items in a collection

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(',')}"

Creating a new collection from a collection

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}

Groovy - next steps

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.

<< 1 2 3 4

Please leave a comment



Search

Blog calendar

blog: previous month September 2010 blog: next month
su mo tu we th fr sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30