Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map leftShift(Map other) method



Description

Groovy Map leftShift(Map other) method overloads the left shift operator provides an easy way to insert one map entries into the map. This allows << to insert maps.

Syntax

public Map leftShift(Map other)

Parameters

other − A Map

Return Value

same map with added entries of passed map.

Example - Inserting A Map entries in a Map of String and String

Following is an example of the usage of this method −

main.groovy

// define two maps
def map = ["A" : "Apple", "B" : "Banana"] 

def map1 = ["C": "Carrot", "D":"Berry"]

// add map1 entries into map 
def result = map << map1

println(result)

Output

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

[A:Apple, B:Banana, C:Carrot, D:Berry]

Example - Inserting A Map entries in a Map of Integer and Integer

Following is an example of the usage of this method −

main.groovy

// define maps
def map = [1 : 11, 2 : 12]

def map1 = [3: 13, 4:14]

// add map1 entries into map 
def result = map << map1

println(result)

Output

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

[1:11, 2:12, 3:13, 4:14]

Example - Inserting A Map entries in 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")] 

def map1 = [3: new Student(3,"Adam"),4: new Student(4,"Markus")]

// add map1 entries into map 
def result = map << map1

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