Grails Cookbook - A collection of tutorials and examples

Groovy Each Loop Examples

This post will show examples on how to use Groovy each() to iterate through objects in a collections.

List Examples

Here are Groovy each() examples applied to List.

Example on iterating over a range of numbers
(1..3).each {
    println "Number ${it}"
}
The code will display:
Number 1
Number 2
Number 3

Example on iterating over a range of numbers but in reverse order
(3..1).each {
    println "Number ${it}"
}
The code will display:
Number 3
Number 2
Number 1

Example on iterating over a range of letters
('a'..'c').each {
    println "Letter ${it}"
}
The code will display:
Letter a
Letter b
Letter c

Example on iterating over a range of letters but in reverse order
('c'..'a').each {
   println "Letter ${it}"
}
The code will display:
Letter c
Letter b
Letter a

Example on a simple list
['Cat', 'Dog', 'Elephant'].each {
    println "Animal ${it}"
}
The code will display:
Animal Cat
Animal Dog
Animal Elephant

Example with customized variable name
Instead of using it, you can specify the variable name that holds the value of an item
['Cat', 'Dog', 'Elephant'].each { animalName ->
    println "Animal ${animalName}"
}

Example with index counter

Sometimes it is useful to know the index of the current item on the list. This is where index counters are useful. Here is an example:
['Cat', 'Dog', 'Elephant'].eachWithIndex { animalName, index ->
    println "${index}. Animal ${animalName}"
}
The code will display this. Take note that index is zero-based, meaning it will start with the value 0.
0. Animal Cat
1. Animal Dog
2. Animal Elephant
An updated logic to start with 1
['Cat', 'Dog', 'Elephant'].eachWithIndex { animalName, index ->
    println "${index+1}. Animal ${animalName}"
}
The code will display:
1. Animal Cat
2. Animal Dog
3. Animal Elephant

Set Example

Here is a simple example to show that Groovy Each can be applied to sets also.

Set<String> testSet = new HashSet<String>()
testSet << 'Apple'
testSet << 'Banana'
testSet << 'Apple'
testSet.each { fruit ->
    println "fruit ${fruit}"
};
Since this is a set, there are no duplicates. Hence this output:
fruit Apple
fruit Banana

Map Examples

Here are Groovy each() examples applied to Maps. To review, a map is a collection of key value pair

Example on a simple map
def testMap = ['cat':'Meow', 'dog':'Woof']
testMap.each { animal, animalSound ->
    println "${animal} has the sound ${animalSound}"
};
Notice that you need to specify the name of the key and it's corresponding value. The output of the code is this:
cat has the sound Meow
dog has the sound Woof

Example with index counter
Similar to list, we can also apply index counters to maps when using Groovy each():
def testMap = ['cat':'Meow', 'dog':'Woof']
testMap.eachWithIndex { animalItem , i ->
    println "${i+1}. ${animalItem.key} has the sound ${animalItem.value}"
};

1. cat has the sound Meow
2. dog has the sound Woof

Other Groovy Tutorials