Tuesday, April 5, 2011

Using findAll Collection Closure in Groovy

I have a "Set" that I need to use the findAll closure upon. The Set contains objects, not just primitive values. For instance... I have a Set of Employee objects and I need to iterate and grab elements of that Set of Empolyee Objects by attributes of the Employee.

For some reason the findAll closure seems to be just ignore my close and returns an empty set.

Here is my syntax;

dstCollection = srcCollection.findAll{
    it.age == 22
}

Any help would be most appreciate.

Thanks.

From stackoverflow
  • The following works for me:

    class Employee {
        int age
    
        String toString() {
            age
        }
    }
    
    def list = [ new Employee(age:22), new Employee(age:23), new Employee(age:22) ] as Set
    
    println list
    println list.findAll { it.age == 22 }
    

    output:

    [22, 23, 22]
    [22, 22]
    

    Can you post your code?

    Edit: added "as Set", since I noticed the question is about sets and not lists. This also works for me.

    Rui Vieira : You are missing a "{" on the toString definition ;-)
  • Thanks so much... works like a charm.

0 comments:

Post a Comment