Groovy Weekend – Collections: Grouping And Summing Items

I’ve been working with Groovy for some time now and I think it’s one of the best languages for the JVM.

To show my love for this language I dedicate this weekend to showcase some of the enhancements Groovy has made to working with Lists, Maps and Collections. Some small tidbits – just for fun.

This is the 7th and last installment of the Groovy Weekend Collections Showcase Reel – at least for this weekend 🙂 which we’ll conclude with grouping, collecting and summing.


sum

sum() is a method on Iterable which ehm,…sums up all items – using the plus() method under the hood.

class Animal {
 String name
 BigDecimal price
 String farmer
 String toString() { name }
}

def animals = []
animals << new Animal(name: "Buttercup", price: 2, farmer: "john")
animals << new Animal(name: "Carmella", price: 5, farmer: "dick")
animals << new Animal(name: "Cinnamon", price: 2, farmer: "dick")

// gather the total price of all animals
assert 9 == animals.sum { it.price }
assert 9 == animals.price.sum()

Putting it all together

// grouping: animals by farmer
def animalsByFarmer = animals.groupBy { it.farmer }
assert "[john:[Buttercup], dick:[Carmella, Cinnamon]]" 
               == animalsByFarmer.toString()

// grouping and summing: total price per farmer
def totalPriceByFarmer = animals
                            .groupBy { it.farmer }
                            .collectEntries { k, v -> 
                                [k, v.price.sum()]
                            }
assert ['john':2, 'dick':7] == totalPriceByFarmer

That’s it – the last edition this weekend! Check out more of Groovy’s methods on Iterable and Collection in the GDK documentation.

No animals were hurt while making these examples. For now, I’ll hope you will enjoy Groovy as much as I do. 🙂