Groovy 5 adds support for using an index variable in a for-in loop. You must define an extra variable as first argument of the for loop. This variable will be used as index variable. For each iteration of the code in the for-in loop the value of this index variable is incremented by 1. You can use this value in the for loop.
The following example shows several uses of an index variable in a for-in loop:
// Range of letters from a up to e. def letters = 'a'..'e' // Store results calculated in for-in loop. def result = [] for (int index, char letter in letters) { // Store key/value pair where index is key and // letter is the value. result << [(index): letter] } assert result == [ [0: 'a'], [1: 'b'], [2: 'c'], [3: 'd'], [4: 'e'] ] // Store results calculated in for-in loop. def numbers = [] for (int index, int number in 10..20) { // Perform calculation with index and number and // add result to numbers. numbers << index * number } assert numbers == [0, 11, 24, 39, 56, 75, 96, 119, 144, 171, 200]
Written with Groovy 5.0.0.