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:"[email protected]")
Person person2=new Person(salary:23000,emailId:"[email protected]")
Person person3=new Person(salary:26000,emailId:"[email protected]")
Person person4=new Person(salary:20000,emailId:"[email protected]")
Person person5=new Person(salary:22000,emailId:"[email protected]")
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 -> [[email protected]:25000, [email protected]:23000, [email protected]:26000, [email protected]:20000, [email protected]:22000]
[/java]
CollectEntries works on any type of Collection-> be it a Map, a list of Objects, Array etc.
Hope it helps 🙂