Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

What is Inject Method in 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?

question from:https://stackoverflow.com/questions/5209149/what-is-inject-method-in-groovy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...