4

I'm trying to use something like the python enumerate() method in groovy.
E.g.:

list = ['book','pencil','laptop','coffee']
for product, line in enumerate(list, 1):
    print "Product %s in the %sth line" % (product, line)

Output should be:
Product book in the 1th line
Product pencil in the 2th line
Product laptop in the 3th line
Product coffee in the 4th line

Is there a way to do the enumerate method in groovy?
Regards!

Alejandro
  • 434
  • 1
  • 3
  • 13

1 Answers1

12
['book','pencil','laptop','coffee'].eachWithIndex { name, i ->     
    println "Product ${name} in the ${i+1} line" 
}
Dónal
  • 185,044
  • 174
  • 569
  • 824
BZ.
  • 1,928
  • 2
  • 17
  • 26