Overview
Loops allow you to iterate through objects in a List in various ways. Click on a Loop method listed below to jump to that section and learn more about what it does, the syntax it requires, and example code.
.each
Loops
- The
.each
method is applied to any List. The actions specified in the code block are applied to each element in the List.
Syntax
collection.each {element ->
//Code to execute for each element in the collection
}
Example 1
This example takes a List of Strings and logs the name of each color in the List using interpolation.
List colors = ['red', 'green', 'blue'] as List
colors.each { color ->
logger.info("Color: ${color}")
}
Example 2
This example is identical to the first, except the element name is omitted. Instead, it
is used. it
can be used when an element is not specified.
List colors = ['red', 'green', 'blue'] as List
colors.each {
logger.info("Color: ${it}")
}
For Loops
- For Loops are very similar to While Loops (see below), but with all 3 components specified as arguments.
Syntax
for(variable declaration; expression; Increment) {
statement #1
statement #2
...
}
Example
- This example sets an integer
i
with a starting value of 0, specifies that this loop should run so long asi
is less than 5, and incrementsi
by 1 after each loop. - This example will start logging numbers at 0. After each loop,
i
increases by 1. The last number displayed in the log will be 4 because oncei
is 5, we no longer meet the condition so the loop stops.
for(int i = 0 as int;i<5;i++){
logger.info(i.toString())
}
For-In Loops
- For-In Loops allow us to name our elements explicitly before we iterate through them. The actions specified in the code block are applied to each element.
Syntax
for (element in collection){
//Code to execute for each element in the collection
}
Example
This example takes a list of integers and logs them using interpolation.
List numbers = [1, 2, 3, 4, 5] as List
for(num in numbers){
logger.info("Number: ${num}")
}
While Loops
- While Loops allow us to continue a process until a break condition is met. For example, we may want to loop through a set of records until we find a specific value.
Syntax
while(condition){
statement #1
statement #2
...
}
Example
This example will start logging numbers at 0. After each loop, the count
variable increases by 1. The last number displayed in the log will be 4 because once count
is 5, we no longer meet the condition, so the loop stops.
int count = 0 as int
while(count<5){
logger.info(count.toString())
count++
}
Related Articles:
Comments
0 comments
Please sign in to leave a comment.