Friday 19 October 2012

Groovy iteration - great resource

Groovy allows you to use "short-written" constructs (such as each or find) to run through lists or easily find one or several items in a list using closures.


Example:
myList.each { item ->
     // do something with the item
     item.doSomething()
}


This says: for each element in my list, I would like to access it using the variable name "item". If the list is typed, the item will be of the type of the elements in the list and its properties and behaviours will be accessible as such. This is how you access item.doSomething() which is declared in the item's class.

The block in curly brackets is called a closure, it will get precompiled into a separate class file, much as anonymous classes in Java get precompiled into separate classes.

You can also for instance find the first occurrence of something using closures as follows:
myList.find { it.temperature == 165 }

This will find the first item in the list which has temperature 165. it is the keyword that lets you access the current element being iterated. Here we're imagining we are working with a class that store (among other things) a temperature value.

You could do the same and find all corresponding items using:
myList.findAll { it.temperature == 165 }


As in the two previous, examples, the piece of code between curly braces is called a closure and will get precompiled to a separate class file.

If this has wet your appetite, try this resource the covers a much more comprehensive range of iteration operations available in Groovy with clean hands-on examples: http://hanuska.blogspot.be/2008/12/easy-groovy-iteration.html.

As you can see there are some really cool one-liners just waiting to be born.

Thoughts?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory