September 13, 2011

Groovy Goodness: Find Elements Matching Groovy Truth

In Groovy 1.8.1 we can use the find() and findAll() methods to find the elements in for example a List wich complies to Groovy truth. The find() and findAll() methods are defined in the Groovy GDK on the Object class, so we can use it for every object that can be iterated.

class User {
    boolean enabled
    Boolean asBoolean() {

def items = [0, false, null, [], [:], '', new User(enabled: false), 'Groovy rocks!', 101]

assert items.find() == 'Groovy rocks!'

assert items.findAll() == ['Groovy rocks!', 101]