Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map leftShift(Entry entry) method



Description

Groovy Map leftShift(Entry entry) 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(Entry entry)

Parameters

entry − a Map.Entry to be added to the Map.

Return Value

same map with added entry.

Example - Inserting an entry in 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 entry into map
def result = map &lt< ["C": "Carrot"]

println(result)

Output

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

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

Example - Inserting an entry in 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 entry into map
def result = map &lt< [3:13]

println(result)

Output

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

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

Example - Inserting an entry in 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")] 

// addv an entry into map 
def result = map << [3: new Student(3,"Adam")]

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 ]]
groovy_maps.htm
Advertisements