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' ]
Groovy - collect() The method collect iterates through a collection, converting each element into a new value using the closure as the transformer.
findAll() Finds the items matching the IDENTITY Closure (i.e. matching Groovy truth). Collection. findAll(Closure closure) Finds all values matching the closure condition.
You need findAll
:
barsOfAllFoos.findAll { it.contains 'baz' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With