Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Inject Method in Groovy?

Tags:

groovy

What does the inject method in Groovy actually do? I googled it, and have not found the exact answer. Can anyone specify its use with a simple example?

like image 563
Ant's Avatar asked Mar 06 '11 06:03

Ant's


1 Answers

It applies an operation to a collection and keeps track of an intermediate value. Take this example: [1, 2, 3, 4].inject(0, { sum, value -> sum + value }). This says use 0 as the initial value and apply the addition operation to the intermediate result and each element in sequence. Each application of the operation generates a new intermediate result. In this case, the closure adds up the numbers, so it generates the sum of the list. You can imagine it like:

<initial value> <operation> <element1> <operation> ... <elementn> 

Or, in the case of [1, 2, 3, 4].inject(0, { sum, value -> sum + value }):

0 + 1 + 2 + 3 + 4 

To find the product of a list, you can use [1, 2, 3, 4].inject(1, { product, value -> product * value}). In this case, 1 is used as the initial value, since it is the identity value for mulitplication.

Here's an example that splits a list of multi-word strings into a flat list of words:

strings = ["", "this", "is a", "test of inject!"] words = strings.inject([], { list, value -> list + value.tokenize() }) assert words == ["this", "is", "a", "test", "of", "inject!"] 

Other terms that are sometimes used to describe this operation are "reduce", as in MapReduce, or a "fold" (specifically a foldl).

like image 100
ataylor Avatar answered Sep 23 '22 14:09

ataylor