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:

[java]

class Person {
Integer salary
String emailId
}

Person person1=new Person(salary:25000,emailId:"anamika@gmail.com")
Person person2=new Person(salary:23000,emailId:"sanjana@gmail.com")
Person person3=new Person(salary:26000,emailId:"khalid@gmail.com")
Person person4=new Person(salary:20000,emailId:"anjali@gmail.com")
Person person5=new Person(salary:22000,emailId:"aditya@gmail.com")
List<Person> persons=[person1,person2,person3,person4,person5]

[/java]

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

[java]

Map<String,Integer> result = persons.collectEntries{
[it.emailId,it.salary]
}

OR

Map<String,Integer> result = persons.collectEntries{
[(it.emailId):it.salary]
}

Output of result -> [anamika@gmail.com:25000, sanjana@gmail.com:23000, khalid@gmail.com:26000, anjali@gmail.com:20000, aditya@gmail.com:22000]

[/java]

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

Hope it helps 🙂

FOUND THIS USEFUL? SHARE IT

Leave a Reply

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