60

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
}
raffian
  • 31,267
  • 26
  • 103
  • 174

2 Answers2

138

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
ataylor
  • 64,891
  • 24
  • 161
  • 189
  • 1
    great answer, where can I find out about closures like `eachWithIndex` and the types of arguments they take? – raffian Mar 01 '12 at 19:56
  • 2
    I'd start here: http://groovy.codehaus.org/GDK+Extensions+to+Object and http://groovy.codehaus.org/JN1015-Collections – ataylor Mar 01 '12 at 20:02
  • Be careful if you need to use `break` or `continue` in such loop – and1er Aug 30 '22 at 11:57
10

Try this if you want to start index 1.

[ 'rohit', 'ravi', 'roshan' ].eachWithIndex { name, index, indexPlusOne = index + 1 ->
    println "Name $name has position $indexPlusOne"
}
Ivar
  • 6,138
  • 12
  • 49
  • 61
R Tiwari
  • 325
  • 3
  • 9