Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify starting value of index in Groovy's eachWithIndex method?

When using Groovy's eachWithIndex method the index value starts at 0, I need it to start at 1. How can I do that?

like image 792
ubiquibacon Avatar asked Nov 23 '25 15:11

ubiquibacon


1 Answers

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
like image 90
tim_yates Avatar answered Nov 25 '25 09:11

tim_yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!