GPars: return of each parameter {}

I want to do many things with each of these example lines and return an Object of a different type here Integers, and then some larger class objects.

Here in this example, I am trying to do something simple, however, I get a completely wrong result. At least for the fact that I was hoping to return. Xd

I was hoping 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 give a short explanation. Thank you very much!

+6
source share
1 answer

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

Do you want collect (return a new collection, causing it to close)

So change

  strings.eachParallel { it.length() } 

to

  strings.collectParallel { it.length() } 

(by the way)

GPars now comes with Groovy, so you don't need @Grab , and I assume you wanted to use the closure variable in 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() } } 
+11
source

All Articles