Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map count(Closure closure) method



Description

Groovy Map count(Closure closure) method count the number of occurences of items which satisfy the given closure.

Syntax

public List count(Closure closure)

Parameters

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

Return Value

the number of occurences

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

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

println(result)

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

println(result)

Output

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

2
2

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

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

println(result)

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

println(result)

Output

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

2
2

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

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

println(result)

// count 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 −

2
2
groovy_maps.htm
Advertisements