Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map toMapString(int size) method



Description

Groovy Map toMapString(int size) method returns the string representation of the map. String representation is limited by maxSize appended with ....

Syntax

public Map toMapString(int size)

Parameters

size − stop after approximately this many characters and append '...'

Return Value

String representation of the map.

Example - Getting String representation 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", "P":"Peach"] 

//get string representation of the Map limited to 10 characters
def result = map.toMapString(10)

// print String
print(result)

Output

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

[A:Apple, B:Banana, ...]

Example - Getting String representation 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, 4: 14, 5: 15] 

// get string representation of the Map limited to 10 characters
def result = map.toMapString(10)

// print String
print(result)

Output

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

[1:11, 2:12, ...]

Example - Getting String representation 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 : new Student(1, "Julie"), 2 : new Student(2, "Robert"),3: new Student(3,"Adam")] 

// get string representation of the Map limited to 10 characters
def result = map.toMapString(10)

// print String
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 ], ...]
groovy_maps.htm
Advertisements