-->

GPars:回报eachParallel的{}(GPars: return of eachParal

2019-08-17 17:37发布

我想要做的东西很多,每个那些例如字符串,返回一些其他类型这里整数的对象,后来一些较大的类的对象。

在这里,在这个例子中,我想简单的东西,我怎么过得到一个完全地错误的结果。 至少对于我希望能找回。 的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()
    }
}

这将是很好,如果答案可以有一个简短的说明。 非常感谢!

Answer 1:

在Groovy中, each (与eachParallel在GPars)返回原来的集合。

你想要的是collect (通过调用关闭返回作出新的集合)

所以,变化

        strings.eachParallel { it.length() }

        strings.collectParallel { it.length() }

(顺便说一句)

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


文章来源: GPars: return of eachParallel{}
标签: groovy gpars