What is Inject Method in Groovy?

前端 未结 1 1132
北恋
北恋 2021-01-31 08:09

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?

相关标签:
1条回答
  • 2021-01-31 08:50

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

    0 讨论(0)
提交回复
热议问题