In the previous tutorial, we learned the basics of Groovy closures — what they are and how to use them. Now, let’s explore one of their most common and powerful use cases: working with collections like Lists and Maps.
Closures simplify collection processing in Groovy, enabling expressive, readable, and concise code. In this tutorial, you’ll learn how to use closures to iterate, transform, and filter Lists and Maps with practical examples.
Preparation
Make sure Groovy is installed. You can use:
- SDKMAN (Linux/macOS):
sdk install groovy
- Groovy Console for interactive editing:
groovyConsole
Online editors like TutorialsPoint Groovy Editor
Using Closures with Lists
Iterating with each
def fruits = ['Apple', 'Banana', 'Orange']
fruits.each { println it }
Output:
Apple
Banana
Orange
You can also use an index:
fruits.eachWithIndex { item, index ->
println "${index}: ${item}"
}
Transforming with collect
Use collect to transform a list:
def upperFruits = fruits.collect { it.toUpperCase() }
println upperFruits // Output: [APPLE, BANANA, ORANGE]
Filtering with find, findAll, any, and every
def numbers = [1, 2, 3, 4, 5, 6]
def even = numbers.find { it % 2 == 0 }
println even // Output: 2
def evens = numbers.findAll { it % 2 == 0 }
println evens // Output: [2, 4, 6]
println numbers.any { it > 5 } // true
println numbers.every { it > 0 } // true
Using Closures with Maps
Maps in Groovy also support closure-friendly methods.
Iterating with each
def person = [name: 'John', age: 30, city: 'New York']
person.each { key, value ->
println "$key => $value"
}
Output:
name => John
age => 30
city => New York
Filtering Maps
def adults = [Anna: 22, Bob: 17, Chris: 19]
def result = adults.findAll { name, age -> age >= 18 }
println result // Output: [Anna:22, Chris:19]
Transforming Maps
def upperNames = adults.collectEntries { name, age ->
[(name.toUpperCase()): age]
}
println upperNames // Output: [ANNA:22, BOB:17, CHRIS:19]
Combining List and Map Operations
Groovy makes it easy to chain operations:
def names = ['jane', 'jack', 'john']
def filtered = names
.findAll { it.startsWith('j') }
.collect { it.capitalize() }
println filtered // Output: [Jane, Jack, John]
Conclusion
Groovy closures make working with Lists and Maps incredibly elegant and readable. Whether you're filtering, transforming, or iterating over collections, closures help you write less code with more power.
The next tutorial will dive into closure scope resolution, including the this, owner, and delegate keywords — key concepts when working with nested or delegated closures.
You can find the full source for this tutorial on our GitHub.
That just the basic. If you need more deep learning about Groovy and Grails you can take the following cheap course:
- Mastering Grails. A Comprehensive Grails Course.
- Groovy Scripting for Developers / Testers
- Introduction to JVM Languages Clojure, Kotlin, and Groovy
Thanks!