Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map max(Closure closure) method



Description

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

Syntax

public Map max(Closure closure)

Parameters

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

Return Value

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

,

Example - Calculating Max 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 max from a map by its value
def result = map.max {it.value}

println(result)

Output

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

C=Carrot

Example - Calculating Max 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 max from a map by its value
def result = map.max {it.value}

println(result)

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

println(result)

Output

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

4=14
4=14

Example - Calculating Max 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 max from a map by its value
def result = map.max {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 −

3=[ 3, Adam ]
groovy_maps.htm
Advertisements