In Groovy, collections are a fundamental part of the language, providing powerful and flexible ways to store and manipulate groups of objects. This section will cover the different types of collections available in Groovy, including lists, maps, and sets, and how to use them effectively.

Key Concepts

  1. Lists: Ordered collections of elements.
  2. Maps: Collections of key-value pairs.
  3. Sets: Unordered collections of unique elements.
  4. Common Operations: Adding, removing, and accessing elements.
  5. Iteration: Looping through collection elements.
  6. Groovy Enhancements: Groovy provides additional methods and syntactic sugar to make working with collections easier.

Lists

Creating Lists

In Groovy, lists are created using square brackets [].

def emptyList = []
def numbers = [1, 2, 3, 4, 5]
def mixedList = [1, "Groovy", true, 3.14]

Accessing Elements

Elements in a list can be accessed using their index, starting from 0.

def numbers = [1, 2, 3, 4, 5]
println(numbers[0]) // Output: 1
println(numbers[2]) // Output: 3

Modifying Lists

You can add, remove, and update elements in a list.

def numbers = [1, 2, 3, 4, 5]
numbers << 6 // Add an element
println(numbers) // Output: [1, 2, 3, 4, 5, 6]

numbers[0] = 10 // Update an element
println(numbers) // Output: [10, 2, 3, 4, 5, 6]

numbers.remove(2) // Remove an element by index
println(numbers) // Output: [10, 2, 4, 5, 6]

Iterating Over Lists

You can iterate over list elements using loops or Groovy's each method.

def numbers = [1, 2, 3, 4, 5]

// Using a for loop
for (num in numbers) {
    println(num)
}

// Using the each method
numbers.each { num ->
    println(num)
}

Maps

Creating Maps

Maps are created using curly braces {} with key-value pairs separated by colons :.

def emptyMap = [:]
def person = [name: "John", age: 30, city: "New York"]

Accessing Elements

Elements in a map can be accessed using their keys.

def person = [name: "John", age: 30, city: "New York"]
println(person['name']) // Output: John
println(person.city) // Output: New York

Modifying Maps

You can add, remove, and update elements in a map.

def person = [name: "John", age: 30, city: "New York"]
person['country'] = 'USA' // Add an element
println(person) // Output: [name:John, age:30, city:New York, country:USA]

person.age = 31 // Update an element
println(person) // Output: [name:John, age:31, city:New York, country:USA]

person.remove('city') // Remove an element
println(person) // Output: [name:John, age:31, country:USA]

Iterating Over Maps

You can iterate over map entries using loops or Groovy's each method.

def person = [name: "John", age: 30, city: "New York"]

// Using a for loop
for (entry in person) {
    println("${entry.key}: ${entry.value}")
}

// Using the each method
person.each { key, value ->
    println("$key: $value")
}

Sets

Creating Sets

Sets are created using the HashSet class or the as Set syntax.

def emptySet = [] as Set
def numbers = [1, 2, 3, 4, 5] as Set
def uniqueNumbers = new HashSet([1, 2, 2, 3, 4, 4, 5])

Accessing Elements

Sets do not support accessing elements by index because they are unordered.

Modifying Sets

You can add and remove elements in a set.

def numbers = [1, 2, 3, 4, 5] as Set
numbers << 6 // Add an element
println(numbers) // Output: [1, 2, 3, 4, 5, 6]

numbers.remove(3) // Remove an element
println(numbers) // Output: [1, 2, 4, 5, 6]

Iterating Over Sets

You can iterate over set elements using loops or Groovy's each method.

def numbers = [1, 2, 3, 4, 5] as Set

// Using a for loop
for (num in numbers) {
    println(num)
}

// Using the each method
numbers.each { num ->
    println(num)
}

Common Operations

Finding Elements

Groovy provides methods like find, findAll, any, and every to search for elements in collections.

def numbers = [1, 2, 3, 4, 5]

def evenNumber = numbers.find { it % 2 == 0 }
println(evenNumber) // Output: 2

def evenNumbers = numbers.findAll { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4]

def hasEven = numbers.any { it % 2 == 0 }
println(hasEven) // Output: true

def allEven = numbers.every { it % 2 == 0 }
println(allEven) // Output: false

Transforming Collections

You can transform collections using methods like collect and collectEntries.

def numbers = [1, 2, 3, 4, 5]

def squares = numbers.collect { it * it }
println(squares) // Output: [1, 4, 9, 16, 25]

def person = [name: "John", age: 30, city: "New York"]
def upperCasePerson = person.collectEntries { key, value ->
    [(key): value.toString().toUpperCase()]
}
println(upperCasePerson) // Output: [name:JOHN, age:30, city:NEW YORK]

Practical Exercises

Exercise 1: List Operations

  1. Create a list of the first 10 natural numbers.
  2. Add the number 11 to the list.
  3. Remove the number 5 from the list.
  4. Print the list.

Solution:

def numbers = (1..10).toList()
numbers << 11
numbers.remove(5)
println(numbers) // Output: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11]

Exercise 2: Map Operations

  1. Create a map with keys name, age, and city.
  2. Add a new key country with the value USA.
  3. Update the age to 31.
  4. Remove the city key.
  5. Print the map.

Solution:

def person = [name: "John", age: 30, city: "New York"]
person['country'] = 'USA'
person.age = 31
person.remove('city')
println(person) // Output: [name:John, age:31, country:USA]

Exercise 3: Set Operations

  1. Create a set of the first 5 natural numbers.
  2. Add the number 6 to the set.
  3. Remove the number 3 from the set.
  4. Print the set.

Solution:

def numbers = [1, 2, 3, 4, 5] as Set
numbers << 6
numbers.remove(3)
println(numbers) // Output: [1, 2, 4, 5, 6]

Conclusion

In this section, we explored the different types of collections in Groovy, including lists, maps, and sets. We learned how to create, access, modify, and iterate over these collections. Additionally, we covered common operations such as finding and transforming elements. By mastering these concepts, you will be well-equipped to handle various data manipulation tasks in Groovy. In the next section, we will delve into closures, a powerful feature of Groovy that allows for concise and expressive code.

© Copyright 2024. All rights reserved