6

これらのサンプル文字列のそれぞれで多くのことを行い、ここで他のタイプのObject Integers、後でいくつかのより大きなクラスオブジェクトを返したいと思います。

この例では、単純なことを試みていますが、完全に間違った結果が得られます。少なくとも私が取り戻したいと思っていたものについては。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()
    }
}

答えに簡単な説明があればいいのにと思います。どうもありがとう!

4

1 に答える 1

12

groovyではeach(およびeachParallelGParsでは)元のコレクションを返します。

あなたが欲しいのはcollect(クロージャーを呼び出すことによって作られた新しいコレクションを返すこと)です

だから、変更

        strings.eachParallel { it.length() }

        strings.collectParallel { it.length() }

(ところで)

GParsはGroovyにバンドルされているので、は必要ありません。変数を?で@Grab使用するつもりだったと思います。closurecollect

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()
  }
}
于 2013-03-19T11:46:45.207 に答える