Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map countBy(Closure closure) method



Description

Groovy Map count(Closure closure) method groups the members of the map into groups determined by the mapping closure and by counting the frequency of created groups.

Syntax

public List countBy(Closure closure)

Parameters

closure − a closure taking one argument as Map.Entry or two arguments as key value pairs. Closure should map entries to frequency count keys.

Return Value

a new Map grouped by keys with frequency counts

Example - Mapping entries of a particular size in 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"] 

// mapping values which are more than 5 characters in size using one argument closure
result = map.countBy{ entry -> entry.value.length() > 5 }

println(result)

// mapping values which are more than 5 characters in size using two arguments closure
result = map.countBy{ key, value -> value.length() > 5 }

println(result)

Output

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

[false:1, true:2]
[false:1, true:2]

Example - Mapping odd 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] 

// mapping values which are odd using one argument closure
result = map.countBy{ entry -> entry.value % 2 != 0 }

println(result)

// mapping values which are odd using two arguments closure
result = map.countBy{ key, value -> value % 2 != 0}

println(result)

Output

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

[true:2, false:1]
[true:2, false:1]

Example - Mapping odd entries of a Map of Integer and Objects

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"), 3 : new Student(3, "Adam")] 

// mapping values which are odd using one argument closure
result = map.count{ entry -> entry.value.getRollNo() % 2 != 0 }

println(result)

// mapping values which are odd using two arguments closure
result = map.count{ key, value -> value.getRollNo() % 2 != 0 }

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 −

[true:2, false:1]
[true:2, false:1]
groovy_maps.htm
Advertisements