Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check two HashMap for equality in Java
To check whether two HashMap are equal or not, use the equals() method.
Let us first create the first HashMap −
// Create hash map 1
HashMap hm1 = new HashMap();
hm1.put("Shirts", new Integer(700));
hm1.put("Trousers", new Integer(600));
hm1.put("Jeans", new Integer(1200));
hm1.put("Android TV", new Integer(450));
hm1.put("Air Purifiers", new Integer(300));
hm1.put("Food Processors", new Integer(950));
Let us now create the second HashMap −
HashMap hm2 = new HashMap();
hm2.put("Shirts", new Integer(700));
hm2.put("Trousers", new Integer(600));
hm2.put("Jeans", new Integer(1200));
hm2.put("Android TV", new Integer(450));
hm2.put("Air Purifiers", new Integer(300));
hm2.put("Food Processors", new Integer(950));
To check whether both the HashMap are equal or not, use the equals() method like this −
hm1.equals(hm2)
The following is an example to check two HashMap for equality −
Example
import java.util.*;
public class Demo {
public static void main(String args[]) {
// Create hash map 1
HashMap hm1 = new HashMap();
hm1.put("Shirts", new Integer(700));
hm1.put("Trousers", new Integer(600));
hm1.put("Jeans", new Integer(1200));
hm1.put("Android TV", new Integer(450));
hm1.put("Air Purifiers", new Integer(300));
hm1.put("Food Processors", new Integer(950));
System.out.println("Map 1 = "+hm1);
// Create hash map 2
HashMap hm2 = new HashMap();
hm2.put("Shirts", new Integer(700));
hm2.put("Trousers", new Integer(600));
hm2.put("Jeans", new Integer(1200));
hm2.put("Android TV", new Integer(450));
hm2.put("Air Purifiers", new Integer(300));
hm2.put("Food Processors", new Integer(950));
System.out.println("Map 2 = "+hm2);
System.out.println("Map 1 is equal to Map 2? "+hm1.equals(hm2));
}
}
Output
Map 1 = {Shirts=700, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600}
Map 2 = {Shirts=700, Food Processors=950, Air Purifiers=300, Jeans=1200, Android TV=450, Trousers=600}
Map 1 is equal to Map 2? trueAdvertisements