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:

  1. Lists: Lists are ordered collections of elements, and they are defined using square brackets [].

Example:

scss
Copy code
def numbers = [1, 2, 3, 4, 5] println(numbers) // prints [1, 2, 3, 4, 5]
  1. Maps: Maps are unordered collections of key-value pairs, and they are defined using curly braces {}.

Example:

scss
Copy code
def ages = [name: "John", age: 30, name: "Jane", age: 25] println(ages) // prints [name:Jane, age:25, name:John, age:30]
  1. Ranges: Ranges represent a sequence of numbers, and they are defined using the .. operator.

Example:

go
Copy code
def range = 1..5 println(range) // prints [1, 2, 3, 4, 5]
  1. For Loop: For loops can be used to iterate over a collection and perform actions on each element.

Example:

scss
Copy code
def numbers = [1, 2, 3, 4, 5] for (number in numbers) { println(number) }
  1. 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:

perl
Copy code
def numbers = [1, 2, 3, 4, 5] def index = 0 while (index < numbers.size()) { println(numbers[index]) index++ }
  1. Each Method: The each method is a convenient way to iterate over a collection and perform actions on each element.

Example:

scss
Copy code
def 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


  • captcha text