DEV Community

ouryperd
ouryperd

Posted on

3 2

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)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay