How to loop in Groovy code examples

This tutorial teaches you various ways to loop in Groovy. The Groovy has the native java looping supports as well some additional stuff for looping.

While loop in Groovy

Groovy supports the java while loop, below is the example

 
package com.java.groovy
 
class GroovyLoopExample {
    static void main(args){
        def x = 0
        def y = 6
        while ( y-- > 0 ) {
            println "Inside while loop x -- $x"
            println "Inside while loop y -- $y"
            x++
        }
        println "Outside while loop x -- $x"// Will print as 10
        println "Outside while loop y -- $y"// Will print as -1
    }
}
 
 

The output of above example

Inside while loop x -- 0

Inside while loop y -- 5

Inside while loop x -- 1

Inside while loop y -- 4

Inside while loop x -- 2

Inside while loop y -- 3

Inside while loop x -- 3

Inside while loop y -- 2

Inside while loop x -- 4

Inside while loop y -- 1

Inside while loop x -- 5

Inside while loop y -- 0

Outside while loop x -- 6

Outside while loop y -- -1

For loop in Groovy

Groovy support the for loop such as Java/C language, The Groovy for loop is used to iterate the elements inside array, list or map.

Below is some examples of for loop in Groovy.

You can use native java for loop as below.

 
 
for (int i = 0; i < 5; i++){
      println i
}
 
//You can iterate over a range as below.
 
def x = 0
for ( i in 0..100 ) {
    println x+i
}
println x
 
//You can iterate over a array as below.
 
 
def array = (0..10).toArray()
x = 0
for ( i in array ) {
    println x+i
}
println x
 
//You can iterate map in for loop as below example
 
 
def map = [1:'a',2:'b',3:'c',4:'d',5:'e']
x = 0
for ( i in map ) {
    println x+i.key
}
println x
 
 

Looping using Closures in Groovy

You can use the Closures in place of most if for loops using each() and eachWithIndex(), Below are some examples of looping using Closures.

 
package com.java.groovy
 
class GroovyClosuresLoopExample {
    static void main(args){
        def list = ['Window', 'Linux', 'Mac']
        def map = [
                    1:'java',
                    2:'C',
                    3:'C++',
                    4:'.Net',
                    5:'PHP',
                    6:'Testing'
                ]
 
        list.each() { println "${it} " };
 
        map.each() { key, value -> println "${key} == ${value}" };
 
        list.eachWithIndex() { obj, i -> println "${i}: ${obj}" };
 
        map.eachWithIndex() { obj, i -> println "${i}: ${obj}" };
    }
}
 
//The output of above example will be as:
 
Window 
Linux 
Mac 
1 == java
2 == C
3 == C++
4 == .Net
5 == PHP
6 == Testing
0: Window
1: Linux
2: Mac
0: 1=java
1: 2=C
2: 3=C++
3: 4=.Net
4: 5=PHP
5: 6=Testing