Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map dropWhile(Closure closure) method



Description

Groovy Map dropWhile(Closure closure) method drops key-value pairs from the map while they satisfy the condition imposed by the closure starting from the first entry of map. If any entry is not satisfying the closue, method ends its execution and resulted map is returned.

Syntax

public Map dropWhile(Closure closure)

Parameters

closure − 1 or 2 args closure that must be satisfied for entries to drop from the map

Return Value

shorted suffix of entries from where closure is not satisfied by the entries.

Example - Dropping 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"] 

// drop entry from map using 1 arg constructor
result = map.dropWhile{it.value.size() < 6}

println(result)

// drop entry from map using 2 args constructor
result = map.dropWhile{key, value -> value.size() < 6}

println(result)

Output

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

[B:Banana, C:Carrot]
[B:Banana, C:Carrot]

Example - Dropping 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: 13] 

// drop entry from map using 1 arg constructor
result = map.dropWhile{it.key % 2  != 0}

println(result)

// drop entry from map using 2 args constructor
result = map.dropWhile{key, value -> key % 2 != 0}

println(result)

Output

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

[2:12, 3:13]
[2:12, 3:13]

Example - Dropping 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"), 3: new Student(3,"Adam")] 

// drop entry from map using 1 arg constructor
result = map.dropWhile{it.key % 2  != 0}

println(result)

// drop entry from map using 2 args constructor
result = map.dropWhile{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 ], 3:[ 3, Adam ]]
[2:[ 2, Robert ], 3:[ 3, Adam ]]
groovy_maps.htm
Advertisements