Groovy supports the usual while {...} loops like Java.
| Code Block |
|---|
def x = 0
def y = 5
while ( y-- > 0 ) {
x++
}
assert x == 5
|
...
The for loop in Groovy is much simpler and works with any kind of array, collection, Map etc.
Note: you can also use the standard Java / C for loop if you wish.
| Code Block |
|---|
// for (int i = 0; i < 5; \i++i) //{ not} implemented by beta-10. // iterate over a range def 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 def 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 def text = "abc" def list = [] for (c in text) { list.add(c) } assert list == ["a", "b", "c"] |
...
In addition, you can use closures in place of most for loops, using each() and eachWithIndex():
| Code Block |
|---|
def stringList = [ "java", "perl", "python", "ruby", "c#", "cobol",
"groovy", "jython", "smalltalk", "prolog", "m", "yacc" ];
def 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
|