Groovy List Common Operations
In Groovy, List is an ordered collection type that can store multiple elements and allow access to these elements in the order they were added. Groovy enhances and simplifies Java's List, providing many convenient methods and syntax for manipulating lists.
Here are some common examples of Groovy list operations:
// Create a List
def list = [1, 2, 3, 4, 5]
// Retrieve elements from the List
def first = list[0]
def last = list[-1]
// Iterate over the List
list.each { println(it) }
// Filter the List (keep only even numbers)
def evenList = list.findAll { it % 2 == 0 }
println(evenList) // Output: [2, 4]
// Transform the List (square each element)
def squareList = list.collect { it * it }
println(squareList) // Output: [1, 4, 9, 16, 25]
// Sort the List in ascending order
def sortedList = list.sort()
println(sortedList) // Output: [1, 2, 3, 4, 5]
// Add elements to the List
list.add(6)
list << 7
list.addAll([8, 9])
println(list) // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
// Remove elements from the List
list.remove(6)
list.removeAll([8, 9])
println(list) // Output: [1, 2, 3, 4, 5, 7]
// Modify an element in the List
list[0] = 0
println(list) // Output: [0, 2, 3, 4, 5, 7]
// Get the size of the List
def size = list.size()
println(size) // Output: 6
In the examples above, we first create a List and add elements to it using the [] operator. Then, we retrieve elements from the list using both the [] operator and the .get() method (though implicit indexing is preferred in Groovy), iterate through each element with the .each() method, filter even numbers using .findAll(), square elements using .collect(), sort the list using .sort(). Subsequently, we add new items via the .add() method and the << operator, remove specific or multiple items using .remove() and .removeAll(), modify existing values through indexing assignment, and finally determine the total count of elements with the .size() method.
It is important to note that Groovy's List supports accessing and modifying elements via the [] operator along with .get() and .set() methods (though direct assignment like [index] = value is idiomatic). It also provides dedicated methods for adding (add, addAll) and removing (remove, removeAll) items. Furthermore, Groovy offers powerful closure-based operations such as .each(), .findAll(), .collect(), and .sort() to perform complex manipulations on lists efficiently.