Groovy, how to iterate a list with an index
94,279
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"
}
Author by
raffian
Applications architect and code slinger since 2000, my background is full stack Java. Reach me at 72616666692e6970616440676d61696c2e636f6d My other passion is landscape photography, check it out if you're interested!
Updated on January 08, 2020Comments
-
raffian over 4 years
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 }