Groovy collectEntries to get a Map from a Collection

15 / Jul / 2015 by Manali Khanna 0 comments

Dealing with collections is a part of a Developer’s daily life. However, sometimes it becomes quite cumbersome when we have to iterate through each collection every time we want a manipulated Collection.

Ever thought of a groovier way to manipulate a collection and get a Map in a single line?

Well, multiple iterations to convert a List to a Map can be saved with collectEntries.
Groovy collectEntries iterates over a collection and return a Map based on the manipulations.

Let us consider a simple class:


class Person {
Integer salary
String emailId

Person person1=new Person(salary:25000,emailId:"")
Person person2=new Person(salary:23000,emailId:"")
Person person3=new Person(salary:26000,emailId:"")
Person person4=new Person(salary:20000,emailId:"")
Person person5=new Person(salary:22000,emailId:"")
List<Person> persons=[person1,person2,person3,person4,person5]


Given a list of Person Objects,to extract a map containing key as Person’s emailId & value as salary, we can use


Map<String,Integer> result = persons.collectEntries{


Map<String,Integer> result = persons.collectEntries{

Output of result -> [,,,,]


CollectEntries works on any type of Collection-> be it a Map, a list of Objects, Array etc.

Hope it helps 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *