Written on
Groovy Quickie: Collection#inject([Object,] Closure)
Groovy has a nice Groovy default method calledinject
[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 })
assert [2, 4, 6, 8, 10, 12, 14] == [1, 2, 3, 4, 5, 6, 7].inject([], { list, value -> list << value * 2; list })
assert 28 == [1, 2, 3, 4, 5, 6, 7].inject { sum, value -> sum + value }