Loading...

Saturday, 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()

6 comments:

Ni said...

Example with 'words' is quite strange. Who will store words with 'commas'?

mrhaki said...

@Ni: The sample is strange indeed, but otherwise the assert statement would be strange if I didn't include the comma's. I included it to demo the plus() method is used for non number elements.

Mykola Golubyev said...

I understood. You know, if it is hard to think of real example with Strings this can only mean you don't need plus for them. Not for strings. Probably for some custom type with overridden plus.

For string it is:
"Languages: " + words.join(', ')

mrhaki said...

@Mykola Golubyev: the String sample didn't feel right indeed. So I have change the sample and used a class with a plus() method to show the sum() method for lists with other members. Thank you for your comments.

Anonymous said...

Bad sample, if you override the plus method you should return a Product object. The sample work with two objects in the collection but try this:

def products = [new Product(name: 'ipod', price: 100), new Product(name: 'rolex', price: 100), new Product(name: 'netbook', price: 100)]

assert 300 == products.sum()

Big misktake!

Hubert Klein Ikkink said...

@Anonymous: You are right. That is why I have written another blogpost Revisited Getting the Sum of Items in a Collection with a return value for the sum() method. I will mention the updated version in this blog post as well.

Post a Comment