You can iterate over a list in below ways.
a.
Using for..in loop
b.
using each function
c.
Using eachWithIndex function
Using for..in loop
HelloWorld.groovy
primes = [2, 3, 5, 7, 11] for (i in primes){ print i + " " }
Output
2 3 5 7 11
Using each function
HelloWorld.groovy
primes = [2, 3, 5, 7, 11] primes.each{ // 'it' is an implicit parameter corresponding to the current element print it + " " }
Output
2 3 5 7 11
Using eachWithIndex
function
HelloWorld.groovy
primes = [2, 3, 5, 7, 11] primes.eachWithIndex{ it, i -> println i + " " + it }
Output
0.2
1.3
2.5
3.7
4.11
No comments:
Post a Comment