Map equals() method in Java with Examples
The java.util.Map.equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.
Syntax:
boolean equals(object obj)
Parameters: The method accepts one parameter obj of this map type and refers to the map whose equality is to be checked with this map.
Return Value: The method returns true if the equality holds for both the object map else it returns false.
Below programs illustrate the java.util.Map.equals() method:
Program 1:
import java.util.*;
public class Map_Demo {
public static void main(String[] args)
{
Map<Integer, String> map1 = new HashMap<Integer, String>();
Map<Integer, String> map2 = new HashMap<Integer, String>();
map1.put( 10 , "Geeks" );
map1.put( 15 , "4" );
map1.put( 20 , "Geeks" );
map1.put( 25 , "Welcomes" );
map1.put( 30 , "You" );
map2.put( 10 , "Geeks" );
map2.put( 15 , "4" );
map2.put( 20 , "Geeks" );
map2.put( 25 , "Welcomes" );
map2.put( 30 , "You" );
System.out.println( "First Map: "
+ map1);
System.out.println( "Second Map: "
+ map2);
System.out.println( "Equality: " + map1.equals(map2));
}
}
|
Output:
First Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Second Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Equality: true
Program 2:
import java.util.*;
public class Map_Demo {
public static void main(String[] args)
{
Map<Integer, String> map1 = new HashMap<Integer, String>();
Map<Integer, String> map2 = new HashMap<Integer, String>();
map1.put( 10 , "Geeks" );
map1.put( 15 , "four" );
map1.put( 20 , "Geeks" );
map1.put( 25 , "Welcomes" );
map1.put( 30 , "You" );
map2.put( 10 , "Geeks" );
map2.put( 15 , "4" );
map2.put( 20 , "Geeks" );
map2.put( 25 , "Welcomes" );
map2.put( 30 , "You" );
System.out.println( "First Map: " + map1);
System.out.println( "Second Map: " + map2);
System.out.println( "Equality: " + map1.equals(map2));
}
}
|
Output:
First Map: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=four}
Second Map: {20=Geek, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Equality: false
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#equals(java.lang.Object)
Last Updated :
23 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...