首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GPars:返回eachParallel{}

GPars:返回eachParallel{}
EN

Stack Overflow用户
提问于 2013-03-19 19:38:29
回答 1查看 10.6K关注 0票数 6

我想对每个示例字符串做很多工作,并返回一些其他类型的对象,这里是整数,稍后返回一些更大的类对象。

在这个例子中,我正在尝试一些简单的东西,无论我如何得到一个完全错误的结果。至少对于我希望得到的东西来说。xD

我希望得到:[6, 5, 6, 5],但是我得到了:[butter, bread, dragon, table]

代码语言:javascript
复制
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()
    }
}

如果答案能有一个简短的解释,那就太好了。非常感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-19 19:46:45

在groovy中,each (GPars中的eachParallel )返回原始集合。

您需要的是collect (通过调用闭包返回新的集合)

所以,改变

代码语言:javascript
复制
        strings.eachParallel { it.length() }

代码语言:javascript
复制
        strings.collectParallel { it.length() }

(顺便说一句)

GPars现在与Groovy捆绑在一起,所以您不需要@Grab,我假设您打算在collect中使用closure变量

代码语言:javascript
复制
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()
  }
}
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15498446

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档