Groovy中的注入方法是什么? [英] What is Inject Method in Groovy?

查看:115
本文介绍了Groovy中的注入方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy中的 inject 方法实际上是做什么的?我用谷歌搜索,但没有找到确切的答案.任何人都可以通过一个简单的示例来指定其用途吗?

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、2、3、4] .inject(0,{sum,value-> sum + value}).也就是说,将0用作初始值,然后将加法运算应用于中间结果和每个元素.该操作的每次应用都会产生一个新的中间结果.在这种情况下,闭包将数字相加,因此将生成列表的总和.您可以像这样想象它:

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>

或者,对于 [1、2、3、4] .inject(0,{sum,value-> sum + value}):

0 + 1 + 2 + 3 + 4

要查找列表的乘积,可以使用 [1、2、3、4] .inject(1,{乘积,值->乘积*值}).在这种情况下,将1用作初始值,因为它是多重复制的标识值.

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!"]

有时用于描述此操作的其他术语是"reduce",如 MapReduce 或折叠"(具体是折叠).

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

这篇关于Groovy中的注入方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆