Groovy, how to iterate a list with an index
With all the shorthand ways of doing things in Groovy, there's got to be an easier way to iterate a list while having access to an iteration index.
for(i in 0 .. list.size()-1) {
println list.get(i)
}
Is there no implicit index in a basic for
loop?
for( item in list){
println item
println index
}
Solution 1:
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
Solution 2:
Try this if you want to start index 1.
[ 'rohit', 'ravi', 'roshan' ].eachWithIndex { name, index, indexPlusOne = index + 1 ->
println "Name $name has position $indexPlusOne"
}