When using Groovy's eachWithIndex method the index value starts at 0, I need it to start at 1. How can I do that?
The index will always start from 0
Your options are:
1) Add an offset to the index:
int offs = 1
list.eachWithIndex { it, idx ->
println "$it @ pos ${idx + offs}"
}
2) Use something other than eachWithIndex (ie: transpose a list of integers starting at 1 with your original list, and then loop through this)
3) You can also use default parameters to hack this sort of thing in... If we pass eachWithIndex a closure with 3 parameters (the two that eachWithIndex is expecting and a third with a default value of index + 1):
[ 'a', 'b', 'c' ].eachWithIndex { item, index, indexPlusOne = index + 1 ->
println "Element $item has position $indexPlusOne"
}
We will give the output:
Element a has position 1
Element b has position 2
Element c has position 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With