groovy - 如何在groovy中编写条件收集?

标签 groovy

想象我有这样的结构:

class Foo {
   String bar
}

现在假设我有几个 Foo 实例,其 bar 值为 baz_1baz_2zab_3

我想编写一个仅收集包含文本 bazbar 值的收集语句。我无法让它工作,但它看起来像这样:

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/

相关文章:

java - org.codehaus.mojo 在 Eclipse 中不可见

java - rest-assured : Cannot get property 'assertionClosure' on null object调用get时出现空指针异常

Groovy 隐式扩展点运算符

logging - 有没有一种干净的方法来记录 Groovy 中方法的结果?

hibernate - Grails域类动态列表作为属性

groovy - 动态向groovy中的对象添加属性或方法

groovy - 在 groovy 中添加 double

grails - 在 grails 中对引用列表进行排序

grails - 在Grails中加载UrlMappingsPlugin时出错

java - 在 Grails 应用程序中使用 Java 代码导致编译永无止境循环