列表中的findAll上的Groovy过滤条件

时间:2013-08-08 21:38:52

标签: groovy findall

我尝试在列表中使用findAll构建动态过滤器。我有一个变量,只有在不为null时才需要包含在过滤器中。

 @Test
    void testSample(){
        def list = [ new Employee(age:22, isManager:false), 
                     new Employee(age:23, isManager:true), 
                     new Employee(age:22, isManager:true) ] as Set

        def var = 22;
        String query1 = "it.age == var && it.isManager == true "
        String query2 = "it.isManager == true"

        println list
        println list.findAll { var ? query1 : query2 } // Should give 1 record age = 22 and manager
        var = null;
        println list.findAll { var ? query1 : query2 } // should give 2 records-only manager

    }

他们两人都提供了所有记录。无论如何,我可以在一个条件下实现这一点而无需编写多个查询吗?

看起来像下面(虽然这不起作用)

println list.findAll{
                if(var) it.age == var &&
                it.isManager == true
        }

1 个答案:

答案 0 :(得分:42)

尝试使用闭包而不是字符串来描述您想要做的事情:

def list = [ new Employee(age:22, isManager:false), 
             new Employee(age:23, isManager:true), 
             new Employee(age:22, isManager:true) ] as Set

def var = 22;
Closure query1 = { it.age == var && it.isManager == true }
Closure query2 = { it.isManager == true }

println list
println list.findAll( var ? query1 : query2 ) // Should give 1 record age = 22 and manager
var = null;
println list.findAll( var ? query1 : query2 ) // should give 2 records-only manager

修改

你的意思是:

println list.findAll{ ( var ? it.age == var : true ) && it.isManager == true }

或更好:

println list.findAll{ ( var != null ? it.age == var : true ) && it.isManager == true }