GPars: return of eachParallel{}

旧城冷巷雨未停 提交于 2019-12-06 01:54:06

问题


I want to do alot of stuff with each of those example strings and return Object of some other type here Integers, later some bigger class-objects.

Here in this example I am trying something simple, how ever I get a completly wrong result. At least for what i was hoping to get back. xD

I hoped to get: [6, 5, 6, 5] but instead I get: [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()
    }
}

It would be nice if the answer could have a short explanation. Thanks a lot!


回答1:


In groovy, each (and eachParallel in GPars) returns the original collection.

What you want is collect (to return the new collection made by calling the closure)

So, change

        strings.eachParallel { it.length() }

to

        strings.collectParallel { it.length() }

(btw)

GPars now comes bundled with Groovy so you shouldn't need the @Grab, and I assume you meant to use your closure variable in the 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()
  }
}


来源:https://stackoverflow.com/questions/15498446/gpars-return-of-eachparallel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!