我试图在列表中使用 findAll 构建动态过滤器。我有一个变量,只有在不为空时才需要包含在过滤器中。
@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
}