Groovy, how to iterate a list with an index

ArraysListGroovyLoops

Arrays Problem Overview


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
}

Arrays Solutions


Solution 1 - Arrays

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 - Arrays

Try this if you want to start index 1.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionraffianView Question on Stackoverflow
Solution 1 - ArraysataylorView Answer on Stackoverflow
Solution 2 - ArraysR TiwariView Answer on Stackoverflow