想象我有这样的结构:
class Foo {
String bar
}
现在假设我有几个 Foo
实例,其 bar
值为 baz_1
、baz_2
和 zab_3
。
我想编写一个仅收集包含文本 baz
的 bar
值的收集语句。我无法让它工作,但它看起来像这样:
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' ]
最佳答案
您需要findAll
:
barsOfAllFoos.findAll { it.contains 'baz' }
关于groovy - 如何在groovy中编写条件收集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12866664/