6

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!

Jakunar
  • 156
  • 1
  • 2
  • 7

1 Answers1

12

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()
  }
}
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 1
    Hi first of all thanks for your reply, your solution works perfectly. Yes I intended to use the closure thanks for the hint! I know that `GPars` should be included with Groovy. And as I am using version 2.1, I don't really get why my Groovy/Grails Tool Suite doesn't accept the import without the `@Grab`. Maybe you have an idea?! Another question not belonging here(sorry) can I some how give me a more fitting nickname? Couldn't find any settings for it. – Jakunar Mar 19 '13 at 13:09
  • 1
    @user2179486 Not sure, I don't use STS, and [does this help](http://meta.stackexchange.com/questions/85818/how-can-i-change-my-name-on-stack-overflow)? – tim_yates Mar 19 '13 at 13:13