Groovy, how to iterate a list with an index Groovy, how to iterate a list with an index arrays arrays

Groovy, how to iterate a list with an index


You can use eachWithIndex:

list.eachWithIndex { item, index ->    println item    println index}

With Groovy 2.4 and newer, you can also use the indexed() method. This can be handy to access the index with methods like collect:

def result = list.indexed().collect { index, item ->    "$index: $item"}println result


Try this if you want to start index 1.

[ 'rohit', 'ravi', 'roshan' ].eachWithIndex { name, index, indexPlusOne = index + 1 ->    println "Name $name has position $indexPlusOne"}