Groovy filter criteria on findAll on a list

后端 未结 1 1933
南旧
南旧 2021-02-05 00:46

I trying to build dynamic filters using findAll on a list. I have a variable that needs to be included in the filter only if not null.

 @Test
    void testSampl         


        
相关标签:
1条回答
  • 2021-02-05 01:05

    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 }
    
    0 讨论(0)
提交回复
热议问题