Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map every(Closure predicate) method



Description

Groovy Map every(Closure predicate) method iterates over each entry of the map and checks if predicates is valid for each entry.

Syntax

public boolean every(Closure predicate)

Parameters

predicate − 1 or 2 arguments closure used for matching

Return Value

true if all entries are valid for the closure

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

// check if all values are string
def result = map.every{entry -> entry.value instanceof String}

println(result)

// check if all values are string
result = map.every{key, value -> value instanceof String}

println(result)

Output

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

true
true

Example - Checking Maps of Integer and Floats

Following is an example of the usage of this method −

main.groovy

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

// check if all values are number
def result = map.every{entry -> entry.value instanceof Number}

println(result)

// check if all values are Integer
result = map.every{key, value -> value instanceof Integer}

println(result)

Output

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

true
true

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

// check if all values are Students
def result = map.every{entry -> entry.value instanceof Student}

println(result)

// check if all values are Student
result = map.every{key, value -> value instanceof Student}

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