Calculate average of list

If you are coming from java, finding the average of a collection of numbers has various flavors using java 8, guava and apache commons. Each has a method which you pass a collection that calculate internally and pass back the average. In groovy, there isn't a method which is left desired for java converts looking for traditional way. Below we show two snippets that show how to calculate the average or mean of a list of numbers using groovy. In both instances, we will call the sum of an arraylist and then divide by the size.

Find average from list

@Test
void average_with_groovy() {

    def numbers = [1, 2, 3, 4]

    def average = numbers.sum() / numbers.size()

    assertEquals 2.5, average
}

Find average with a method

def findAverage(list) { list.sum() / list.size() }

@Test
void average_with_groovy_call_method() {

    def numbers = [1, 2, 3, 4]

    assertEquals 2.5, average(numbers)
}