Here are Groovy each() examples applied to List.
(1..3).each { println "Number ${it}" }The code will display:
Number 1 Number 2 Number 3
(3..1).each { println "Number ${it}" }The code will display:
Number 3 Number 2 Number 1
('a'..'c').each { println "Letter ${it}" }The code will display:
Letter a Letter b Letter c
('c'..'a').each { println "Letter ${it}" }The code will display:
Letter c Letter b Letter a
['Cat', 'Dog', 'Elephant'].each { println "Animal ${it}" }The code will display:
Animal Cat Animal Dog Animal Elephant
['Cat', 'Dog', 'Elephant'].each { animalName -> println "Animal ${animalName}" }
['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 ElephantAn 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
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
Here are Groovy each() examples applied to Maps. To review, a map is a collection of key value pair
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
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