The structures you’ve seen so far have evaluated a Boolean test once and changed the path of execution once based on the result of the condition. Looping, on the other hand, repeats the execution of a block of code multiple times. The loops available in Groovy are while and for , both of which we cover here.
Looping with while:
The while construct is like its Java counterpart. The only difference is the one you’ve seen already—the power of Groovy Boolean test expressions. To summarize very briefly, the Boolean test is evaluated, and if it’s true, the body of the loop is then executed. The test is then re-evaluated, and so forth. Only when the test becomes false does control proceed past the while loop. Listing 6.8 shows an example that removes all entries from a list.
- Listing 6.8 Example while loops
Looping with for:
Considering it is probably the most commonly used type of loop, the for loop in Java is relatively hard to use, when you examine it closely. Through familiarity, people who have used a language with a similar structure (and there are many such languages) grow to find it easy to use, but that is solely due to frequent use, not due to good design. Although the nature of the traditional for loop is powerful, it is rarely used in a way that can’t be more simply expressed in terms of iterating through a collection-like data structure. Groovy embraces this simplicity, leading to probably the biggest difference in control structures between Java and Groovy.
Groovy for loops follow this structure:
where variable may optionally have a declared type. The Groovy for loop iterates over the iterable. Frequently used iterables are ranges, collections, maps, arrays, iterators, and enumerations. In fact, any object can be an iterable. Groovy applies the same logic as for object iteration, described in chapter 8.
Curly braces around the body are optional if it consists of only one statement. Listing 6.9 shows some of the possible combinations.
- Listing 6.9 Multiple for loop examples
You can use it to print a file line-by-line via
* Groovy Document > Control Structures > Looping