Looping in Groovy can be done in several ways. We can use the standard classic Java for loop or use the newer Java for-each loop. But Groovy adds more ways to loop several times and execute a piece of code. Groovy extends the Integer
class with the step()
, upto()
and times()
methods. These methods take a closure as a parameter. In the closure we define the piece of code we want to be executed several times.
If we have a List
in Groovy we can loop through the items of the list with the each()
and eachWithIndex()
methods. We also need to pass a closure as parameter to the methods. The closure is then executed for every item in the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | // Result variable for storing loop results. def result = '' // Closure to fill result variable with value. def createResult = { if (!it) { // A bit of Groovy truth: it == 0 is false result = '0' } else { result += it } } // Classic for loop. for (i = 0 ; i < 5 ; i++) { createResult(i) } assert '01234' == result // Using int.upto(max). 0 . upto ( 4 , createResult) assert '01234' == result // Using int.times. 5 . times (createResult) assert '01234' == result // Using int.step(to, increment). 0 . step 5 , 1 , createResult assert '01234' == result // Classic while loop. def z = 0 while (z < 5 ) { createResult(z) z++ } assert '01234' == result def list = [ 0 , 1 , 2 , 3 , 4 ] // Classic Java for-each loop. for ( int i : list) { createResult(i) } assert '01234' == result // Groovy for-each loop. for (i in list) { createResult(i) } assert '01234' == result // Use each method to loop through list values. list. each (createResult) assert '01234' == result // Ranges are lists as well. ( 0 .. 4 ). each (createResult) assert '01234' == result // eachWithIndex can be used with closure: first parameter is value, second is index. result = '' list. eachWithIndex { listValue, index -> result += "$index$listValue" } assert '0011223344' == result |