Groovy Weekend – Collections: Finding Items In a Collection

I’ve been working with Groovy for some time now and I think it’s one of the best languages for the JVM.

To show my love for this language I dedicate this weekend to showcase some of the enhancements Groovy has made to working with Lists, Maps and Collections. Some small tidbits – just for fun.

In this 3rd installment of the Groovy Weekend Collections Showcase Reel…

find and findAll

find() and findAll() are methods on Collection to find items which match the criteria of a specified closure according to the Groovy Truth.

class Animal {
    String name
    int age
    String toString() { name }

def animals = []
animals << new Animal(name: "Buttercup", age: 2)
animals << new Animal(name: "Carmella", age: 5)
animals << new Animal(name: "Cinnamon", age: 2)

// find first matching animal 
Animal foundAnimal = animals.find { it.age == 2 }
assert == "Buttercup"

// find all matching animals
List foundAnimals = animals.findAll { "C" } 
assert foundAnimals.toString() == "[Carmella, Cinnamon]"

I use these methods a lot! There are some overloaded variants of find and findAll. Check out Groovy’s GDK documentation.