Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map collect(Closure transform) method



Description

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

Syntax

public List collect(Closure transform)

Parameters

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

Return Value

resultant list of transformed values

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 List using one argument closure
result = map.collect{ entry -> entry.key +":" + entry.value }

println(result)

// transform entries of map to List using two arguments closure
result = map.collect{ key,value -> key +":" + value }

println(result)

Output

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

[A:Apple, B:Banana, C:Carrot]
[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 List using one argument closure
result = map.collect{ entry -> entry.key * entry.value }

println(result)

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

println(result)

Output

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

[11, 24, 39]
[11, 24, 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 List using one argument closure
result = map.collect{ entry -> entry.key +":" + entry.value }

println(result)

// transform entries of map to List using two arguments closure
result = map.collect{ key,value -> key +":" + value }

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:[ 1, Julie ], 2:[ 2, Robert ]]
[1:[ 1, Julie ], 2:[ 2, Robert ]]
groovy_maps.htm
Advertisements