Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map findAll(Closure predicate) method



Description

Groovy Map findAll(Closure predicate) method finds and returns all entries matching the given predicate.

Syntax

public Map findAll(Closure predicate)

Parameters

predicate − 1 or 2 arguments closure used for matching

Return Value

Map of all matching entries.

Example - Finding matching entries 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 entries starting from B using one argument closure
def result = map.findAll{entry -> entry.value.startsWith("B")}

println(result)

// find entries starting from B using two arguments closure
result = map.findAll{key, value -> value.startsWith("B")}

println(result)

Output

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

[B:Banana, D:Berry]
[B:Banana, D:Berry]

Example - Finding matching entries 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 even entries using one argument closure
def result = map.findAll{entry -> entry.key % 2 == 0}

println(result)

// find even entries using two arguments closure
result = map.findAll{key, value -> key % 2 ==0}

println(result)

Output

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

[2:12, 4:14]
[2:12, 4:14]

Example - Finding matching entries 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"),4: new Student(4,"Markus")] 

// find first even entry using one argument closure
def result = map.findAll{entry -> entry.key % 2 == 0}

println(result)

// find first even using two arguments closure
result = map.findAll{key, value -> key % 2 ==0}

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 −

[2:[ 2, Robert ], 4:[ 4, Markus ]]
[2:[ 2, Robert ], 4:[ 4, Markus ]]
groovy_maps.htm
Advertisements