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)
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
23 Feb, 2022
Like Article
Save Article