Alejandro
Alejandro

Reputation: 571

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!

Upvotes: 4

Views: 2636

Answers (1)

BZ.
BZ.

Reputation: 1946

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

Upvotes: 12

Related Questions