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 2nd installment of the Groovy Weekend Collections Showcase Reel…


collect

collect() is a method on Collection to iterate on its elements, transforming the values – specified by a closure – and returning them in a new List.

 
class Animal {
    String name
    int age
}

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

// collect on List
def names = animals.collect { it.name }
assert names == ["Buttercup", "Carmella", "Cinnamon"] 
// names is java.util.ArrayList

You can also collect as a different type e.g. a Set, keeping only unique values, while passing this Set as a 1st parameter, and the closure 2nd.

 
assert animals.collect(new HashSet()) { it.age }.toString() == "[2, 5]"

There are many overloaded variants of collect. Check out Groovy’s GDK documentation.

Advertisements