Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map drop(int num) method



Description

Groovy Map drop(int num) method drops given number of key-value pairs from the map from the head of the map if available.

Syntax

public Map drop(int num)

Parameters

num − the number of entries to be removed from the map

Return Value

map consisting keys except the removed one

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 1 entry
result = map.drop(1)

println(result)

// drop 2 entries
result = map.drop(2)

println(result)


// drop 3 entries
result = map.drop(3)

println(result)


// drop 4 entries
result = map.drop(4)

println(result)

Output

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

[B:Banana, C:Carrot]
[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 1 entry
result = map.drop(1)

println(result)

// drop 2 entries
result = map.drop(2)

println(result)


// drop 3 entries
result = map.drop(3)

println(result)


// drop 4 entries
result = map.drop(4)

println(result)

Output

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

[2:12, 3:13]
[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 1 entry
result = map.drop(1)

println(result)

// drop 2 entries
result = map.drop(2)

println(result)


// drop 3 entries
result = map.drop(3)

println(result)


// drop 4 entries
result = map.drop(4)

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 ]]
[3:[ 3, Adam ]]
[:]
[:]
groovy_maps.htm
Advertisements