There are several types of loops in groovy. Following are some of the ways:

List list = [4, 2, 9, 6, 7, 8, 2]

  • for loop:
    for (int i = 0; i < list.size(); i++) {
      print list.get(i)
    }
    output = 4296782
    
    for (int i : list) {
      print i
    }
    output = 4296782
    
    for (int i in list) {
      print i
    }
    output = 4296782
    
  • while loop:
    int i = 0
    while (i < list.size()) {
      print list.get(i++)
    }
    output = 4296782
    
  • each loop: iterate whole list
    list.each {
      print it
    }
    output = 4296782
    
  • eachWithIndex loop: iterate whole list, also provide index of element iterating
    list.eachWithIndex { val, index ->
      print "${val}${index}"
    }
    output = 40219263748526
    
  • times loop: repeat a code block in given times
    5.times{
      print "M"
    }
    output = MMMMM
    
  • upto loop: iterate from one number to another
    6.upto(10, {
       print it
    })
    output = 678910
    
  • step loop: iterate from one number to another with specific increment
    0.step 25, 5,{
      print it
    }
    output = 05101520
    

Hope this helps 🙂 .