How to Write Loops in Groovy

Loops are important in data processing because so often we need to process repeating items of data, such as items in a list. Groovy offer several looping structures including the while and for loops. In this topic, we will have some fun with Groovy loops and consider printing the names of popular singers.

To learn how to write loops in Groovy follow these 3 steps:

  1. Open your text editor and type in the following lines of Groovy code:
    def singers = ["Adele", "Barry Manilow", "Rhianna", "Tim McGraw", "Elton John"]
    def i = 0
    println ("Using a while loop:")
    while (i < singers.size()) {
    	println ("${singers[i++]}")
    println ("Using a for loop:")
    for (String singer : singers) {
    	println ("${singer}")
    The program begins by defining a list of popular singers called singers. Next, a while is demonstrated so that we can print each singer's name. Note that the condition within parentheses must evaluate to true in order to continue the loop logic. The index, i, is incremented within the loop so that at some point the value of i will be equal to the number of elements in the loop and therefore the loop will terminate. After the while loop, a for will be executed. Each element of the list will be successively loaded into the variable singer until all items in the list have been printed.
  2. Save your file as WriteLoops.groovy.
  3. In the command prompt, type in the command to interpret and run your script:
    Run loops script
    The output displays the result of each loop execution, i,e, the name of each singer we have stored in the list.
Author: Stephen Withrow

Stephen has over 30 years of experience in training, development, and consulting in a variety of technology areas including Python, Java, C, C++, XML, JavaScript, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen has a degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.