Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Groovy filter criteria on findAll on a list

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 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

    }

Both of them giving all the records. Is there anyway I can achieve this in one condition without need to write muiltiple queries ?

Looking some like below (this doesn't work though)

println list.findAll{
                if(var) it.age == var &&
                it.isManager == true
        }
question from:https://stackoverflow.com/questions/18136616/groovy-filter-criteria-on-findall-on-a-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...