DEV Community

ouryperd
ouryperd

Posted on

Add avg() to List in Groovy

List.metaClass.avg = {
    return delegate.size() ? delegate.sum() / delegate.size() : 0
}
Enter fullscreen mode Exit fullscreen mode

Use:

assert [1, 2, 3].avg() == 2

Top comments (0)