Loops
Prerequisites: Groovy Truth and if statements
Groovy supports Java's loops and adds shorter ones based on methods.
for-in
for (fruit in ['apple', 'banana', 'cherry']) {
println fruit
}
for (i in 1..3) {
print "$i "
}
println()
apple
banana
cherry
1 2 3
for (x in collection) loops over any list, range, map, string, or
array. println() with empty parentheses prints just a new line.
Counting loops
3.times { print "Hip! " }
println 'Hooray!'
1.upto(4) { print "$it " }
println()
10.downto(7) { print "$it " }
println()
0.step(10, 3) { print "$it " }
println()
for (int i = 0; i < 3; i++) {
print "i=$i "
}
println()
Hip! Hip! Hip! Hooray!
1 2 3 4
10 9 8 7
0 3 6 9
i=0 i=1 i=2
times, upto, downto, and step take a closure — the block in
braces — and call it with each number as it. The classic Java for
loop works too.
while
def balance = 1000
def years = 0
while (balance < 2000) {
balance *= 1.07
years++
}
println "Doubled after $years years: ${balance.setScale(2, java.math.RoundingMode.HALF_UP)}"
Doubled after 11 years: 2104.85
Groovy also supports Java's do { ... } while (condition) loop, which
runs its body at least once.
break and continue
for (n in 1..10) {
if (n % 2 == 0) continue // skip even numbers
if (n > 7) break // stop the loop
print "$n "
}
println()
1 3 5 7
Common mistakes
- Using
breakorcontinueinsideeach { }ortimes { }— they are closures, not loops, sobreakis a compile error there andreturnonly skips to the next item. When you need to stop early, usefor (x in ...), orfind/any(Level 2).
Practice
Print the multiplication table for 7, from 7 x 1 = 7 to
7 x 5 = 35.
Show solution
1.upto(5) { i ->
println "7 x $i = ${7 * i}"
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
i -> names the closure's parameter instead of using it.