Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map findResult(Closure predicate) method



Description

Groovy Map findResult(Closure predicate) method finds and returns first matching non-null result by passing each entry to the closure, otherwise null is returned.

Syntax

public Object findResult(Closure predicate)

Parameters

predicate − 1 or 2 arguments closure used for matching

Return Value

the first entry found

Example - Finding first match 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", "D":"Berry"] 

// find first match starting from B using one argument closure
def result = map.findResult{ if(it.value.startsWith("B")) return "Found ${it.key}:${it.value}"}

println(result)

// find first match starting from B using two arguments closure
result = map.findResult{key, value -> if(value.startsWith("B")) return "Found ${key}:${value}"}

println(result)

Output

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

Found B:Banana
Found B:Banana

Example - Finding first match in a Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

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

// find first even entry using one argument closure
def result = map.findResult{if(it.value % 2 == 0) return "Found ${it.key}:${it.value}"}

println(result)

// find first even entry using two arguments closure
result = map.findResult{key, value -> if(value % 2 == 0) return "Found ${key}:${value}"}

println(result)

Output

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

Found 2:12
Found 2:12

Example - Finding First match in a Map of String and Object

Following is an example of the usage of this method −

main.groovy

// define maps
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert"), 3: new Student(3,"Adam")] 

// find first even entry using one argument closure
def result = map.findResult{if(it.key % 2 == 0) return "Found ${it.key}:${it.value}"}

println(result)

// find first even entry using two arguments closure
result = map.findResult{key, value -> if(key % 2 == 0) return "Found ${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 −

Found 2:[ 2, Robert ]
Found 2:[ 2, Robert ]
groovy_maps.htm
Advertisements