Loading...

April 24, 2010

Groovy Goodness: Sum the Values in a Object Array

Since Groovy 1.7.1 we can use the sum() method on an array of objects. We already could use it for collections and iterators, but this has been extended to array of objects. The sum() can take a closure as an argument. The result of the closure is used to add the values together. Finally we can use an initial value for the sum.

def n = 0..5 as Integer[]

assert n instanceof Integer[]
assert      0 + 1 + 2 + 3 + 4 + 5 == n.sum()
assert 10 + 0 + 1 + 2 + 3 + 4 + 5 == n.sum(10)
assert      0 + 10 + 20 + 30 + 40 + 50 == n.sum { it * 10 }
assert 10 + 0 + 10 + 20 + 30 + 40 + 50 == n.sum(10, { it * 10 })