Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map min(Closure closure) method



Description

Groovy Map min(Closure closure) method selects an entry in map having minimum calculated using closure. If more than one value is fulfilling criteria, an arbitrary choice is made between entries having minimum value. In case closure is accepting two parameters, we can implement it as traditional comparator.

Syntax

public Map min(Closure closure)

Parameters

closure − 1 or 2 args closure used to determine correct ordering.

Return Value

Map.Entry value having minimum value as determined by the closure.

,

Example - Calculating min in a map of String, String

Following is an example of the usage of this method −

main.groovy

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

// get min from a map by its value
def result = map.min {it.value}

println(result)

Output

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

A=Apple

Example - Calculating min in a map of Integer, Integer

Following is an example of the usage of this method −

main.groovy

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

// get min from a map by its value
def result = map.min {it.value}

println(result)

// get min from a map by comparing multiple value
result = map.min {a, b -> a.value <=> b.value}

println(result)

Output

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

1=11
1=11

Example - Calculating min in a map of Integer, 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"),3: new Student(3,"Adam")] 

// get min from a map by its value
def result = map.min {it.value}

println(result)

class Student implements Comparable {
   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 + " ]"
   }
   
   public int compareTo(Object obj){
      Student s = (Student)obj;
      return this.rollNo - s.rollNo   
   }
}

Output

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

1=[ 1, Julie ]
groovy_maps.htm
Advertisements