Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map plus(Map entries) method



Description

Groovy Map plus(Map entries) method returns a new map containing entries from current map and passed entries. If there is any common entry, then the map entry takes precedence.

Syntax

public String plus(Map entries)

Parameters

entries − A Map of entries to be added to the map

Return Value

A new map containing all key-value pairs from self and entries collection passed.

Example - Concatenating Entries of a Map to 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"] 

// add a Map to the map
def result = map + [ "C":"Carrot", "A":"Avacado" ]

println(result)

Output

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

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

Example - Concatenating Entries of a Map to 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]

// add a Map to the map
def result = map + [ 2:22, 3:33 ]

println(result)

Output

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

[1:11, 2:22, 3:33]

Example - Concatenating Entries of a Map to 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")] 

// add a Map to the map
def result = map + [3 : new Student(3, "Markus") ]

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 −

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