Ways of Iteration in Groovy

Other topics

How can I do something n times?

How can I print hello world 5 times?

5.times{
    println "hello world"
}

Each and EachWithIndex

each and eachWithIndex are methods to iterate over collections.

each have it(default iterator) and eachWithIndex have it,index(default iterator, default index).

We can also change the default iterator/index. Please see below examples.

def list = [1,2,5,7]
list.each{
    println it
}

list.each{val->
    println val
}

list.eachWithIndex{it,index->
    println "value " + it + " at index " +index
}

Contributors

Topic Id: 9844

Example Ids: 30290,32092

This site is not affiliated with any of the contributors.