Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a conditional collect in groovy?

Tags:

groovy

Imagine I have this structure:

class Foo {    String bar } 

Now imagine I have several instance of Foo whose bar value is baz_1, baz_2, and zab_3.

I want to write a collect statement that only collects the bar values which contain the text baz. I cannot get it to work, but it would look something like this:

def barsOfAllFoos = Foo.getAll().bar assert barsOfAllFoos == [ 'baz_1', 'baz_2', 'zab_3' ] def barsWithBaz = barsOfAllFoos.collect{ if( it.contains( "baz" ) { it } ) } // What is the correct syntax for this? assert barsWithBaz == [ 'baz_1', 'baz_2' ] 
like image 484
ubiquibacon Avatar asked Oct 12 '12 20:10

ubiquibacon


People also ask

How does Groovy collect work?

Groovy - collect() The method collect iterates through a collection, converting each element into a new value using the closure as the transformer.

What is find findAll and it in groovy?

findAll() Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth). Collection. findAll(Closure closure) Finds all values matching the closure condition.


1 Answers

You need findAll:

barsOfAllFoos.findAll { it.contains 'baz' } 
like image 96
tim_yates Avatar answered Sep 24 '22 05:09

tim_yates