How to Write Loops in Groovy

  • google plus

In Brief...

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.

Instructions

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' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss