Groovy filter criteria on findAll on a list

…衆ロ難τιáo~ 提交于 2019-12-03 00:59:31
tim_yates

Try with Closures rather than Strings describing what you want to do:

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

Edit

Do you mean:

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

Or better:

println list.findAll{ ( var != null ? it.age == var : true ) && it.isManager == true }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!