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.

In this 7th installment of the Groovy Weekend Collections Showcase Reel…


inject

inject() is a method on Collection which iterates all elements, passing 1st item to specified closure, injecting results back into closure with 2nd item, etc

First an abstract example:

assert 1 * 2 * 3 * 4 == 
    [1, 2, 3, 4].inject { current, val -> current * val }

And – as you would expect by now – some animals:

class Animal {
    String name
    BigDecimal price
    String farmer
}

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, passing initial price of 0
assert 9 == animals.inject(0) { totalPrice, animal -> 
    totalPrice + animal.price 
}
// or...
assert 9 == animals.price.inject(0) { totalPrice, price -> 
    totalPrice + price
}

There are some variants of inject, one which takes an initial value and one which takes the head of the collection as initial value. Check out Groovy’s GDK documentation.