Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map containsKey(Object key) method



Description

Groovy Map containsKey(Object key) method checks if Map contains this key.

Syntax

public Map containsKey(Object key)

Parameters

key − the key to search for.

Return Value

True or false depending on whether the key value is there or not.

Example - Checking 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"] 

// check if keys exist
println(map.containsKey("TopicName")) 
println(map.containsKey("Topic"))

Output

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

true
false

Example - Checking 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"] 

// check if keys exist
println(map.containsKey(1))
println(map.containsKey(3)) 

Output

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

true
false

Example - Checking 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")] 

// check if keys exist
println(map.containsKey(1)) 
println(map.containsKey(3)) 

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 −

true
false
groovy_maps.htm
Advertisements