Groovy

Using Groovy

Language Guide

Groovy Features

Modules

Examples

Useful Links

IDE Support

Support

Community

Developers

Tools we use

IntelliJ IDEA
YourKit profiler

Feeds


Site
News
Looping

Groovy supports the usual while {...} and do {...} while loops like Java.

x = 0
y = 5

while ( y-- > 0 ) {
    x++
}

assert x == 5

x = 0
y = 5

do {
	x++
} 
while ( --y > 0 )

assert x == 5

for loop

The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc.

// iterate over a range
x = 0
for ( i in 0..9 ) {
    x += i
}
assert x == 45

// iterate over a list
x = 0
for ( i in [0, 1, 2, 3, 4] ) {
    x += i
}
assert x == 10

// iterate over an array
array = (0..4).toArray()
x = 0
for ( i in array ) {
    x += i
}
assert x == 10

// iterate over a map
map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
    x += e.value
}
assert x == 6

// iterate over values in a map
x = 0
for ( v in map.values() ) {
    x += v
}
assert x == 6

// iterate over the characters in a string
text = "abc"
list = []
for (c in text) {
    list.add(c)
}
assert list == ["a", "b", "c"]

closures

In addition, you can use closures in place of most for loops, using each() and eachWithIndex():

stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
               "groovy", "jython", "smalltalk", "prolog", "m", "yacc"  ];

stringMap  = [ "Su" : "Sunday", "Mo" : "Monday", "Tu" : "Tuesday",
               "We" : "Wednesday", "Th" : "Thursday", "Fr" : "Friday",
               "Sa" : "Saturday" ];

stringList.each() { print " ${it}" };  println "";
// java perl python ruby c# cobol groovy jython smalltalk prolog m yacc

stringMap.each() { key, value | println "${key} == ${value}" };
// Su == Sunday
// We == Wednesday
// Mo == Monday
// Sa == Saturday
// Th == Thursday
// Tu == Tuesday
// Fr == Friday

stringList.eachWithIndex() { obj, i | println " ${i}: ${obj}" };
// 0: java
// 1: perl
// 2: python
// 3: ruby
// 4: c#
// 5: cobol
// 6: groovy
// 7: jython
// 8: smalltalk
// 9: prolog
// 10: m
// 11: yacc

stringMap.eachWithIndex() { obj, i | println " ${i}: ${obj}" };
// 0: Su=Sunday
// 1: We=Wednesday
// 2: Mo=Monday
// 3: Sa=Saturday
// 4: Th=Thursday
// 5: Tu=Tuesday
// 6: Fr=Friday