Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map collectEntries(Closure transform) method



Description

Groovy Map collectEntries(Closure transform) method iterates through the Map entries and transform them using transform closure to return a Map of transformed entries.

Syntax

public Map collectEntries(Closure transform)

Parameters

transform − a transformer closure taking one argument as Map.Entry or two arguments as key value pairs.

Return Value

resultant map of transformed entries

Example - Transforming entries of a Map of String and String

Following is an example of the usage of this method −

main.groovy

// define a map
def map = ["A" : "Apple", "B" : "Banana", "C": "Carrot"] 

// transform entries of map to Map using one argument closure
result = map.collectEntries{ entry -> [entry.value, entry.key] }

println(result)

// transform entries of map to Map using two arguments closure
result = map.collectEntries{ key,value ->  [key, value.toUpperCase()] }

println(result)

Output

When we run the above program, we will get the following result −

[Apple:A, Banana:B, Carrot:C]
[A:APPLE, B:BANANA, C:CARROT]

Example - Transforming entries of a Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : 11, 2 : 12, 3: 13] 

// transform entries of map to Map using one argument closure
result = map.collectEntries{ entry -> [entry.value, entry.key] }

println(result)

// transform entries of map to Map using two arguments closure
result = map.collectEntries{ key,value -> [value, key * value] }

println(result)

Output

When we run the above program, we will get the following result −

[11:1, 12:2, 13:3]
[11:11, 12:24, 13:39]

Example - Transforming entries of a Map of Integer and Object

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert")] 

// transform entries of map to Map using one argument closure
result = map.collectEntries{ entry -> [entry.value, entry.key] }

println(result)

// transform entries of map to List using two arguments closure
result = map.collectEntries{ key,value -> [value, key] }

println(result)

class Student{
   int rollNo
   String name

   Student(int rollNo, String name){
      this.rollNo = rollNo
      this.name = name
   }

   @Override
   public boolean equals(Object obj) {
      Student s = (Student)obj
      return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name)
   }
   
   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]"
   }
}

Output

When we run the above program, we will get the following result −

[[ 1, Julie ]:1, [ 2, Robert ]:2]
[[ 1, Julie ]:1, [ 2, Robert ]:2]
groovy_maps.htm
Advertisements