Groovy — Transforming collections with closures
Use closures to describe which values to keep, how to transform them, and how to combine the results.
A simple example
Call one closure
- Start with Argument 2
- Do this Apply n times 2
- Result 4
def twice = { n -> n * 2 }
println(twice(2))
4
Filter, transform, and reduce a list
findAll keeps positive readings, collect doubles them, and inject combines the doubled values starting from zero. These eager list transformations make each intermediate result easy to print.
A sensor sends −1 for a failed reading, followed by 4 and 7. Filter out the failure and double the two valid readings to change their scale. Adding 8 and 14 gives a report total of 22.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
def readings = [-1, 4, 7]
def doubled = readings.findAll { it > 0 }.collect { it * 2 }
println doubled
println doubled.inject(0) { sum, value -> sum + value }
[8, 14] 22
The program drops −1, doubles 4 and 7, and sums 8 and 14 to get 22.
Try it yourself
What if every reading is negative?
Check your answer
The transformed list is empty. The initial value passed to inject makes its sum zero.