Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map putAll(Collection entries) method



Description

Groovy Map putAll(Entries entries) method allows to add multiple entries to a Map.

Syntax

public Map putAll(Collection entries)

Parameters

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

Return Value

Current map with entries of collection passed.

Example - Adding multiple entries 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 entries to the map
map.putAll(["C":"Carrot", "A":"Avacado"])

println(map)

Output

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

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

Example - Adding multiple entries 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 entries to the map
map.putAll([ 2:22, 3:33 ])

println(map)

Output

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

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

Example - Adding multiple entries 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
map.putAll([3 : new Student(3, "Markus") ])

println(map)

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