Search code examples
groovyenumerate

Enumerate list in groovy


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!


Solution

  • ['book','pencil','laptop','coffee'].eachWithIndex { name, i ->     
        println "Product ${name} in the ${i+1} line" 
    }