GPars: return of eachParallel{}
Asked Answered
M

1

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!

Mimimimic answered 19/3, 2013 at 11:38 Comment(0)
E
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()
  }
}
Eucalyptus answered 19/3, 2013 at 11:46 Comment(2)
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.Mimimimic
@user2179486 Not sure, I don't use STS, and does this help?Eucalyptus

© 2022 - 2024 — McMap. All rights reserved.