Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map any(Closure predicate) method



Description

Groovy Map any(Closure predicate) method iterates over the entries of the map and checks if predicate is valid for at least one of the entry. If a single parameter is passed to Closure, it is passed as Map.Entry. If two values are passed to predicate then these values will be passed as key and value.

Syntax

public boolean any(Closure predicate)

Parameters

predicate − 1 or 2 arg closure predicate used to match key-value pairs

Return Value

true if any of the entry is matching the given predicate

Example - Checking entries of 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"] 

// compare first char of each value with key
result = map.any{ entry -> entry.key == entry.value.substring(0,1) }

println(result)

// compare first char of each value with key
result = map.any{ key,value -> key == value.substring(0,1) }

println(result)

Output

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

true
true

Example - Checking 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: 6] 

// compare value with key
result = map.any{ entry -> entry.value == entry.key * 2 }

println(result)

// compare value with key
result = map.any{ key,value -> value == key * 2 }

println(result)

Output

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

true
true

Example - Checking entries of a Map of Integer and 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")] 

// compare value with key
result = map.any{ entry -> entry.key == entry.value.getRollNo() }

println(result)

// compare value with key
result = map.any{ key,value -> key == value.getRollNo() }

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
true
groovy_maps.htm
Advertisements