Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map get(Object key, Object defaultValue) method



Description

Groovy Map get(Object key) method looks up the key in this Map and return the corresponding value. If there is no entry in this Map for the key, then defaultValue is returned. It also adds the defaultValue and Key to the Map.

Syntax

public Object containsKey(Object key, Object defaultValue)

Parameters

key − the key to search for retrieval.

defaultValue − the default Value to return.

Return Value

The key-value pair or defaultValue if it does not exist.

Example - Getting Value based on key from a Map of String and String

Following is an example of the usage of this method −

main.groovy

// define a map
def map = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"] 

// get the value
println(map.get("TopicName", "Empty")) 
println(map.get("Topic", "Empty"))

Output

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

Maps
Empty

Example - Getting Value based on key from a Map of Integer and String

Following is an example of the usage of this method −

main.groovy

// define a map
def map = [1 : "Apple", 2 : "Banana"] 

// get the value
println(map.get(1,"Empty")) 
println(map.get(3,"Empty")) 

Output

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

Apple
Empty

Example - Getting Value based on key from 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")] 

// get the value
println(map.get(1,new Student(-1, "")))
println(map.get(3,new Student(-1, "Noname")))

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, Julie ]
[ -1, Noname ]
groovy_maps.htm
Advertisements