The Groovy times is one of the simplest and most useful method for looping in Groovy. This is very helpful if you know exactly how many times you want to loop and the syntax is as simple as it get. Here are some examples.
Groovy times is my favorite way of looping because it can't get any simpler than this. Here is an example:
5.times { println "Groovy Rules!" }
This will execute the body 5 times! Here is the sample output:
Groovy Rules! Groovy Rules! Groovy Rules! Groovy Rules! Groovy Rules!
It is not required that the number of times is literal. We may use variables for flexibility! For example:
def n = 3 n.times { println "Hello World" }Here is the output:
Hello World Hello World Hello World
3.times { println "Hello " + it }
This will print this output:
Hello 0 Hello 1 Hello 2
You may also give a name to it for readability. Here is an example:
3.times { idx -> println "Test " + idx }
Here is the output:
Test 0 Test 1 Test 2
This is useful when we are performing inner loops. For example:
3.times { x -> 2.times { y -> println "X = " + x + " Y = " + y } }
This will output:
X = 0 Y = 0 X = 0 Y = 1 X = 1 Y = 0 X = 1 Y = 1 X = 2 Y = 0 X = 2 Y = 1