Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map take(int num) method



Description

Groovy Map take(int num) method returns a new map containing the first num entries from the head of the map.

Syntax

public Map take(int num)

Parameters

num − number of elements to take from the map

Return Value

A map containing first num entries of map.

Example - Getting first few 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"] 

// get first two entries
result = map.take(2)

// print sub map
print(result)

Output

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

[A:Apple, B:Banana]

Example - Getting first few entries from 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] 

// get first two entries
result = map.take(2)

// print sub map
print(result)

Output

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

[1:11, 2:12]

Example - Getting first few entries from 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")] 

// get first two entries
result = map.take(2)

// print sub map
print(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 −

[1:[ 1, Julie ], 2:[ 2, Robert ]]
groovy_maps.htm
Advertisements