Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map collectMany(Object collector, Closure projection) method



Description

Groovy Map collectMany(Object collector, Closure projection) method iterates through the Map entries and flattens the resultant collections adding them to a collector.

Syntax

public Object collectMany(Object Collector, Closure projection)

Parameters

  • collector − initial collection to add the projected items to.

  • projection − a projecting closure taking two arguments as key value pairs to return a collection of items.

Return Value

a collector with the projected collections concatenated/flattened to it.

Example - Flattening 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"] 

// Flattening entries of map to List 
result = map.collectMany(['X']){ key,value -> key.startsWith('B') ? value.toList() : []  }

println(result)

Output

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

[X, B, a, n, a, n, a]

Example - Flattening 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] 

// Flattening entries of map to List 
result = map.collectMany([]){ key,value -> [key, value] }

println(result)

Output

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

[1, 11, 2, 12, 3, 13]

Example - Flattening 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")] 

// Flattening entries of map to List 
result = map.collectMany([]){ 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 ]]
groovy_maps.htm
Advertisements