Dark theme | Light theme

December 12, 2009

Groovy Goodness: Getting the Sum of Items in a Collection

Update for this post Revisited Getting Sum of Items in a Collection.

In Groovy we can sum up the elements in a Collection with the sum() methods. We can use the variant without arguments, but also the one with one argument. The argument is the initial value for the sum value. The sum() method invokes the plus() method on the elements in the collection.

def numbers = [1, 2, 3, 4, 5, 6]
assert 21 == numbers.sum()
assert 31 == numbers.sum(10)

class Product {
    String name
    BigDecimal price

    BigDecimal plus(Product other) {
        price + other.price
def products = [new Product(name: 'laptop', price: 999), new Product(name: 'netbook', price: 395)]

assert 1394 == products.sum()