The equals() method of Map interface in Java is used to check if two maps are equal. Two maps are considered equal if they meet the following conditions.
- Both maps must have the same size.
- Both maps must contain identical key-value pairs. (It means every key in one map must be associated with the same value as in the other map)
Syntax of equals() Method
public boolean equals(Object o)
- Parameter: This method takes an object "o" which is compared with equality with the current map.
- Return Type: This method returns "true" if the specified object is equal to the current map, otherwise it returns "false".
Example: This example demonstrates how to use the equals() method to check if two HashMap objects have identical key-value pairs.
// Java Program to demonstrates the working of equals()
import java.util.HashMap;
import java.util.Map;
public class Geeks {
public static void main(String[] args)
{
// Create the first HashMap and
// add key-value pairs
Map<Integer, String> hm1 = new HashMap<>();
hm1.put(1, "Geek1");
hm1.put(2, "Geek2");
hm1.put(3, "Geek3");
// Create the second HashMap
// and add key-value pairs
Map<Integer, String> hm2 = new HashMap<>();
hm2.put(1, "Geek1");
hm2.put(2, "Geek2");
hm2.put(3, "Geek3");
// Create the Third HashMap
// and add key-value pairs
Map<Integer, String> hm3 = new HashMap<>();
hm3.put(1, "Geek1");
hm3.put(2, "Geek4");
hm3.put(3, "Geek5");
System.out.println("First HashMap: " + hm1);
System.out.println("Second HashMap: " + hm2);
// Compare the First and the
// Second HashMap for equality
System.out.println("Are the maps equal? "
+ hm1.equals(hm2));
System.out.println("First HashMap: " + hm1);
System.out.println("Third HashMap: " + hm3);
// Compare the First and the
// Third HashMap for equality
System.out.println("Are the maps equal? "
+ hm1.equals(hm3));
}
}
Output:
