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


collectEntries

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

 
class Farmer { String name }
class Animal {
    String name
    Farmer farmer
}

def john = new Farmer(name: "John")
def dick = new Farmer(name: "Dick")

def animals = []
animals << new Animal(name: "Buttercup", farmer: john)
animals << new Animal(name: "Carmella", farmer: dick)
animals << new Animal(name: "Cinnamon", farmer: dick)

// collect farmer name by animal name
def results = animals.collectEntries { animal -> 
 [animal.name, animal.farmer.name]
}
assert results == ['Buttercup':'John', 
 'Carmella':'Dick', 
 'Cinnamon':'Dick']

 


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