【问题标题】:GPars: return of eachParallel{}GPars:返回 eachParallel{}
【发布时间】:2013-03-19 19:46:45
【问题描述】:

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

在这个例子中,我正在尝试一些简单的事情,但我得到了一个完全错误的结果。 至少对于我希望得到的东西。 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()
    }
}

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

【问题讨论】:

    标签: groovy gpars


    【解决方案1】:

    在 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()
      }
    }
    

    【讨论】:

    • 您好,首先感谢您的回复,您的解决方案完美运行。是的,我打算使用关闭感谢您的提示!我知道GPars 应该包含在 Groovy 中。由于我使用的是 2.1 版,我真的不明白为什么我的 Groovy/Grails Tool Suite 不接受没有 @Grab 的导入。也许你有一个想法?!另一个不属于这里的问题(对不起)我可以给我一个更合适的昵称吗?找不到任何设置。
    • @user2179486 不确定,我不使用 STS,does this help?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-14
    相关资源
    最近更新 更多