我想对每个示例字符串做很多工作,并返回一些其他类型的对象,这里是整数,稍后返回一些更大的类对象。
在这个例子中,我正在尝试一些简单的东西,无论我如何得到一个完全错误的结果。至少对于我希望得到的东西来说。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()
}
}如果答案能有一个简短的解释,那就太好了。非常感谢!
发布于 2013-03-19 19:46:45
在groovy中,each (GPars中的eachParallel )返回原始集合。
您需要的是collect (通过调用闭包返回新的集合)
所以,改变
strings.eachParallel { it.length() }至
strings.collectParallel { it.length() }(顺便说一句)
GPars现在与Groovy捆绑在一起,所以您不需要@Grab,我假设您打算在collect中使用closure变量
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()
}
}https://stackoverflow.com/questions/15498446
复制相似问题