Groovy Quickie: Collection#inject([Object,] Closure)

Groovy has a nice Groovy default method called inject [0]. Inject can be executed on collection types and is used for algorithms having intermediate results that need to be passed from iteration to iteration. Documentation excerpt:
Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as foldLeft or reduce in functional parlance.
Let's say we wanted to compute the sum of a list of numbers:
 
assert 28 == [1, 2, 3, 4, 5, 6, 7].inject(0, { sum, value -> sum + value })
 
The code above iterates over all list elements, and passes the current list element as the second actual argument to the given closure. The first argument resembles the intermediary result. 1. run: sum == 0 (initial value), value == 1 2. run: sum == 1, value == 2 3. run: sum == 3, value == 3 4. run: sum == 6, value == 4 // ... inject does not only work for scalar values, but for arbitrary data types:
 
assert [2, 4, 6, 8, 10, 12, 14] == [1, 2, 3, 4, 5, 6, 7].inject([], { list, value -> list << value * 2; list })
 
In fact, we could even simplify the code above to use the second inject without the initial value argument:
 
assert 28 == [1, 2, 3, 4, 5, 6, 7].inject { sum, value -> sum + value }
 

Conclusion

The Collection#inject default Groovy method (DGM) comes in handy whenever we need to iterate over a collection and pass some intermediary result from iteration to iteration. It can be used either be specifying an initial value and a closure, or with just a single closure as argument.

[0] DGM: Collection#inject