Groovy Weekend – Collections: Sorting and Grouping Items

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


groupBy() is a method on Iterable to group items according to a mapping closure. You’ll get a LinkedHashMap grouped by the key returned by the closure.

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

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

// single closure
Map animalsByCountry = animals.groupBy { }
assert animalsByCountry["NL"].size() == 2 // Buttercup and Carmella
assert animalsByCountry.BE.size() == 1 // Cinnamon

There’s also an option to pass multiple closures.

Map animalsByCountryAndAge = 
        animals.groupBy( [{ }, { it.age }] )
assert animalsByCountryAndAge.toString() == 
        "[NL:[2:[Buttercup], 5:[Carmella]], BE:[2:[Cinnamon]]]"

There are some overloaded variants of groupBy. Check out Groovy’s GDK documentation.