Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Map equals(Map map) method



Description

Groovy Map equal(Map map) method compares maps for equality while coercing the numerical values.

Syntax

public boolean equals(Map map)

Parameters

map − map being compared to

Return Value

true if content of both maps are identical.

Example - Checking Maps of String and String for Equality

Following is an example of the usage of this method −

main.groovy

// define maps
def map = ["A" : "Apple", "B" : "Banana", "C": "Carrot"] 
def map1 = ["A" : "Apple", "B" : "Banana", "C": "Carrot"] 
def map2 = ["A" : "APPLE", "B" : "Banana", "C": "Carrot"] 

println(map.equals(map1))
println(map.equals(map2))

Output

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

true
false

Example - Checking Maps of Integer and Floats for Equality

Following is an example of the usage of this method −

main.groovy

// define maps
def map = [1 : 11, 2 : 12, 3: 13]
def map1 = [1 : 11.0, 2 : 12.0, 3: 13.0]
def map2 = [1 : 11L, 2 : 12L, 3: 13L] 

println(map.equals(map1))
println(map.equals(map2))

Output

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

true
true

Example - Checking Maps of String and Object for Equality

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"), 3: new Student(3,"Adam")] 
def map1 = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert"), 3: new Student(3,"Adam")] 
def map2 = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert")] 

println(map.equals(map1))
println(map.equals(map2))

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