Lesson contents

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

  1. Start with Argument 2
  2. Do this Apply n times 2
  3. Result 4
The closure stores a calculation in a variable. Calling it with 2 evaluates the calculation.
Lesson.groovy
def twice = { n -> n * 2 }
println(twice(2))
Output
4
Advertisements

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.

Valid readings: 4 and 7. After scaling: 8 and 14. Sum: 22.
Build a sensor report

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
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 }
Output
[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.

Groovy language documentation

Related tags

  • Groovy
  • closures
  • collections
  • reduction