Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map retainAll(Closure closure) method



Description

Groovy Map retainAll(Closure closure) method retains entries from the Map where entries are satifying the closure and removes other entries.

Syntax

public Object retainAll(Closure closure)

Parameters

closure − a one or two args closure to be applied on entries.

Return Value

Current map with entries retained and rest removed.

Example - Retaining multiple entries from 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" ] 

// retain entries from map whose size is more than 5 and remove others
map.retainAll{it.value.size() > 5}

println(map)

Output

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

[B:Banana, C:Carrot]

Example - Retaining multiple entries from a Map of Integer and 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]

// retain even entries from map 
map.retainAll{key, value -> value % 2 == 0}

println(map)

Output

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

[2:12, 4:14]

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

// retain even entries from map 
map.retainAll{it.value.getRollNo() % 2 == 0}

println(map)

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