How to loop over in Groovy script?

Member

by natalia , in category: Other , 3 years ago

How to loop over in Groovy script?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 3 years ago

@natalia Just use for loop to loop over the collection, array in Groovy, code as example;


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def languages = ["Groovy", "Python", "Java", "PHP"]

for (int i = 0; i < languages.size(); i++) {
    println languages[i]
}
// Output:
// Groovy
// Python
// Java
// PHP

Member

by jenifer , 2 years ago

@natalia 

In Groovy, you can loop over collections or ranges using a range operator or a for loop.

  1. Range Operator:


Groovy provides a range operator .. that creates a range of numbers or characters. You can use it to loop over a range of values.


Examples:


Loop over a range of numbers:

1
2
def nums = 1..5
nums.each { println it }


Output:

1
2
3
4
5
1
2
3
4
5


Loop over a range of characters:

1
2
def letters = 'a'..'d'
letters.each { println it }


Output:

1
2
3
4
a
b
c
d


  1. For Loop:


You can use a for loop to loop over a collection or a range.


Example:


Loop over a list of names:

1
2
3
4
def names = ['John', 'Mary', 'Mark', 'Lisa']
for (name in names) {
  println "Hello, $name!"
}


Output:

1
2
3
4
Hello, John!
Hello, Mary!
Hello, Mark!
Hello, Lisa!


Loop over a range of numbers:

1
2
3
for (i in 1..5) {
  println "Number: $i"
}


Output:

1
2
3
4
5
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5


In both examples, the for loop iterates over each element in the collection or range and executes the code block for each iteration.

Related Threads:

How to loop over xml tags using groovy script?
How to loop over xml child nodes using groovy script?
How to get an array item using script runner groovy script?
How to for loop in Groovy?
How to use flags in a bash script with for loop?