Groovy Collection - Set, List, Map, Range
Published: (December 30, 2025 at 10:25 PM EST)
2 min read
Source: Dev.to
Source: Dev.to
Set
// Creating a Set
def Set1 = [1, 2, 1, 4, 5, 9] as Set
Set Set2 = new HashSet(['a', 'b', 'c', 'd'])
// Modifying a Set
Set2.add(1)
Set2.add(9)
Set2.addAll([4, 5]) // Set2: [1, d, 4, b, 5, c, a, 9]
Set2.remove(1)
Set2.removeAll([4, 5]) // Set2: [d, b, c, a, 9]
// Union of Set
Set Union = Set1 + Set2 // Union: [1, 2, 4, 5, 9, d, b, c, a]
// Intersection of Set
Set intersection = Set1.intersect(Set2) // Intersection: [9]
// Complement of Set
Set Complement = Union.minus(Set1) // Complement: [d, b, c, a]
List
// Creating a List
def list1 = ['a', 'b', 'c', 'd']
def list2 = [3, 2, 1, 4, 5] as List
// Reading a List
println list1[1] // Output: b
println list2.get(4) // Output: 5
// println list1.get(5) // Throws IndexOutOfBoundsException
// Sort a List
println list2.sort() // Output: [1, 2, 3, 4, 5]
// Reverse a List
println list1.reverse() // Output: [d, c, b, a]
// Finding elements
println ("Max:" + list2.max() + ":Last:" + list1.last())
// Output: Max:5:Last:d
println list2.find({ it % 2 == 0 }) // Output: 2
println list2.findAll({ it % 2 == 0 }) // Output: [2, 4]
Map
// Two equivalent notations
Map m1 = [name: "Groovy"]
// Map m1 = ["name": "Groovy"] // same as above
// Using a variable as a key
String s1 = "name"
Map m2 = [(s1): "Groovy"]
def m3 = [id: 1, title: "Mastering Groovy"] as Map
println m3.get("id") // 1
println m3["id"] // 1
// Example with predicates
ageMap.any { entry -> entry.value > 25 } // true if any entry satisfies
ageMap.every { entry -> entry.value > 18 } // true only if all entries satisfy
Range
def range1 = 1..10
Range range2 = 'a'..'e'
// Iteration
range1.each { println it }
// Validation
println range1.any { it > 5 } // true
println range1.every { it > 0 } // true
// Step
List l1 = range1.step(2) // Output: [1, 3, 5, 7, 9]
// Properties
println range1.getFrom() // 1
println range1.getTo() // 10
println range1.isReverse() // false (checks if the range is decreasing)