February 12, 2020

Groovy Goodness: Calculate Average For Collection

Groovy 3 adds the average method to collections to calculate the average of the items in the collections. When the items are numbers simply the average is calculated. But we can also use a closure as argument to transform an item into a number value and then the average on that number value is calculated.

In the following example code we use the average method on a list of numbers and strings. And we use a closure to first transform an element before calculating the average:

def numbers = [10, 20, 30, 40, 50]

assert numbers.average() == 30

// We can use a closure to transform an item
// and the result is used for calculating an average.
assert numbers.average { n -> n / 10 } == 3

def words = ['Groovy', 'three', 'is', 'awesome']

// Use supported Java method reference syntax to first 
// get length of word.
assert words.average(String::size) == 5

// Calculate average number of vowels in the words.
assert words.average { s -> s.findAll(/a|e|i|o|u/).size() } == 2.25

Written with Groovy 3.0.0.