Groovy Set Methods
In Groovy, a Set is an unordered collection type that can store multiple elements and does not preserve duplicate elements. Groovy enhances and simplifies Java's Set, providing many convenient methods and syntax for manipulating Sets.
Here are some common examples of Groovy Set operations:
// Create a Set
def set = [1, 2, 3, 4, 5] as Set
// Add elements
set.add(6)
set << 7
set.addAll([8, 9])
println(set) // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] (order may vary)
// Remove elements
set.remove(6)
set.removeAll([8, 9])
println(set) // Output: [1, 2, 3, 4, 5, 7] (order may vary)
// Check for element existence
def contains = set.contains(3)
println(contains) // Output: true
// Get the size of the Set
def size = set.size()
println(size) // Output: 6
In the examples above, we first create a Set and use the as operator to convert a list into a set. Then, we add elements using the add method and the << operator; multiple elements are added via the addAll method. Elements in the Set can be removed individually or collectively using the remove and removeAll methods, respectively. We then use the contains method to check if a specific element exists within the set, and the size method is used to retrieve the total number of elements.
It is important to note that Groovy's Set does not allow duplicate elements; therefore, attempting to add an existing element has no effect on the collection. The Set supports adding and removing elements through methods such as add, addAll, remove, and removeAll. It also provides a contains method for checking element presence. Furthermore, Groovy allows using closures to perform more complex operations on Sets.