我想对每个示例字符串做很多事情,并在此处返回一些其他类型的对象(整数),然后返回一些更大的类对象。
在这个例子中,我正在尝试一些简单的事情,但我得到了完全错误的结果。
至少对于我希望得到的东西。 xD
我希望得到:[6, 5, 6, 5]
但我得到的是:[butter, bread, dragon, table]
package test
@Grab(group='org.codehaus.gpars', module='gpars', version='1.0.0')
import static groovyx.gpars.GParsPool.withPool
class Test {
List<String> strings = new ArrayList<String>([
"butter",
"bread",
"dragon",
"table"
])
def closure = { it.length() }
def doStuff() {
def results = withPool( 4 ) {
strings.eachParallel{ it.length()}
}
println results
}
static main(args) {
def test = new Test()
test.doStuff()
}
}
如果答案能有一个简短的解释就好了。
多谢!
在时髦中,each
(and eachParallel
在 GPars 中)返回原始集合。
你想要的是collect
(返回通过调用闭包创建的新集合)
所以,改变
strings.eachParallel { it.length() }
to
strings.collectParallel { it.length() }
(btw)
GPars 现在与 Groovy 捆绑在一起,因此您不需要@Grab
,我假设你打算使用你的closure
变量在collect
?
package test
import static groovyx.gpars.GParsPool.withPool
class Test {
List<String> strings = [ "butter", "bread", "dragon", "table" ]
def closure = { it.length() }
def doStuff() {
def results = withPool( 4 ) {
strings.collectParallel closure
}
println results
}
static main( args ) {
def test = new Test()
test.doStuff()
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)