Show List
Groovy Collections and Iteration
Collections in Groovy are data structures that allow you to store and manage multiple values in a single entity. Groovy provides several built-in collection classes, including lists, maps, ranges, and more.
Iteration is the process of repeating a set of statements for each element in a collection. Groovy provides several ways to iterate over collections, including for loops, while loops, and each() method.
Here are some examples of Groovy collections and iteration:
- Lists: Lists are ordered collections of elements, and they are defined using square brackets
[]
.
Example:
scssCopy codedef numbers = [1, 2, 3, 4, 5] println(numbers) // prints [1, 2, 3, 4, 5]
- Maps: Maps are unordered collections of key-value pairs, and they are defined using curly braces
{}
.
Example:
scssCopy codedef ages = [name: "John", age: 30, name: "Jane", age: 25] println(ages) // prints [name:Jane, age:25, name:John, age:30]
- Ranges: Ranges represent a sequence of numbers, and they are defined using the
..
operator.
Example:
goCopy codedef range = 1..5 println(range) // prints [1, 2, 3, 4, 5]
- For Loop: For loops can be used to iterate over a collection and perform actions on each element.
Example:
scssCopy codedef numbers = [1, 2, 3, 4, 5] for (number in numbers) { println(number) }
- While Loop: While loops can also be used to iterate over a collection, but they continue to iterate as long as a certain condition is true.
Example:
perlCopy codedef numbers = [1, 2, 3, 4, 5] def index = 0 while (index < numbers.size()) { println(numbers[index]) index++ }
- Each Method: The
each
method is a convenient way to iterate over a collection and perform actions on each element.
Example:
scssCopy codedef numbers = [1, 2, 3, 4, 5] numbers.each { println(it) }
These are the basic concepts of Groovy collections and iteration, and they allow you to work with multiple values and perform operations on them.
Leave a Comment