HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Collections Framework / Java HashMap / How to compare two hashmaps in Java

How to compare two hashmaps in Java

Learn to compare two hashmaps in Java by keys, values and key-value pairs. Also learn to compare while allowing or restricting duplicate values.

1. Compare hashmap for same key-values – HashMap.equals()

By default, HashMap.equals() method compares two hashmaps by key-value pairs. It means both hashmap instances must have exactly same key-value pairs and both must be of same size.

The order of key-value pairs can be different and does not play in role in comparison.

import java.util.HashMap;

public class HashMapExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        HashMap<Integer, String> map1 = new HashMap<>();

        map1.put(1, "A");
        map1.put(2, "B");
        map1.put(3, "C");
        
        //Same as map1
        HashMap<Integer, String> map2 = new HashMap<>();

 		map2.put(3, "C");
        map2.put(1, "A");
        map2.put(2, "B");
        
        //Different from map1
        HashMap<Integer, String> map3 = new HashMap<>();

        map3.put(1, "A");
        map3.put(2, "B");
        map3.put(3, "C");
        map3.put(3, "D");
        
        System.out.println(map1.equals(map2));  //true
        System.out.println(map1.equals(map3));  //false
    }
}

Program output.

true
false

2. Compare two hashmaps for same keys – HashMap.keySet()

2.1. Are both hashmaps equal?

If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap.keySet() function. It returns all the map keys in HashSet.

We can compare the hashset of keys for both maps using Set.equals() method. It returns true if the two sets have the same size, and every element of the specified set is contained in another set.

import java.util.HashMap;

public class HashMapExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        HashMap<Integer, String> map1 = new HashMap<>();

        map1.put(1, "A");
        map1.put(2, "B");
        map1.put(3, "C");
        
        //Same keys as map1	
        HashMap<Integer, String> map2 = new HashMap<>();

 		map2.put(3, "C");
        map2.put(1, "A");
        map2.put(2, "B");
        
        //Different keys than map1
        HashMap<Integer, String> map3 = new HashMap<>();

        map3.put(1, "A");
        map3.put(2, "B");
        map3.put(3, "C");
        map3.put(3, "D");
        
        System.out.println( map1.keySet().equals( map2.keySet() ));  //true
        System.out.println( map1.keySet().equals( map3.keySet() ));  //false
    }
}

Program output.

true
false

2.2. Find out extra keys

We may be interested in finding out what extra keys first hashmap has than second hashmap. So get this difference, first do a union of keys from both hashmaps, and then remove all keys present in first hashmap.

Java program to find out the difference between two hashmaps.

//map 1 has 3 keys
HashMap<Integer, String> map1 = new HashMap<>();

map1.put(1, "A");
map1.put(2, "B");
map1.put(3, "C");

//map 2 has 4 keys
HashMap<Integer, String> map2 = new HashMap<>();

map2.put(1, "A");
map2.put(2, "B");
map2.put(3, "C");
map2.put(4, "C");

//Union of keys from both maps
HashSet<Integer> unionKeys = new HashSet<>(map1.keySet());
unionKeys.addAll(map2.keySet());

unionKeys.removeAll(map1.keySet());

System.out.println(unionKeys);

Program output.

[4]

3. Compare hashmaps for values – HashMap.values()

If we want to compare hashmaps by values i.e. two hashmaps will be equals if they have exactly same set of values. Please note that HashMap allows duplicate values, so decide if you want to compare hashmaps with duplicate or without duplicate values.

3.1. Duplicates are NOT allowed

Add all values from HashMap.values() to an arraylist for both maps. Now compare both arraylists for equality.

HashMap<Integer, String> map1 = new HashMap<>();

map1.put(1, "A");
map1.put(2, "B");
map1.put(3, "C");

//Same values as map1
HashMap<Integer, String> map2 = new HashMap<>();

map2.put(4, "A");
map2.put(5, "B");
map2.put(6, "C");

//Different values than map1 - C is added twice
HashMap<Integer, String> map3 = new HashMap<>();

map3.put(1, "A");
map3.put(2, "B");
map3.put(3, "C");
map3.put(4, "C");

System.out.println( new ArrayList<>( map1.values() ).equals(new ArrayList<>( map2.values() )) );       //true
System.out.println( new ArrayList<>( map1.values() ).equals(new ArrayList<>( map3.values() )) );       //false

Program output.

true
false

3.2. Duplicates are allowed

If you want to remove duplicate values before comparing the hashmaps, the add all values into a HashSet which automatically ignores duplicate values.

HashMap<Integer, String> map1 = new HashMap<>();

map1.put(1, "A");
map1.put(2, "B");
map1.put(3, "C");

//Same values as map1
HashMap<Integer, String> map2 = new HashMap<>();

map2.put(4, "A");
map2.put(5, "B");
map2.put(6, "C");

//Duplicate values  - C is added twice
HashMap<Integer, String> map3 = new HashMap<>();

map3.put(1, "A");
map3.put(2, "B");
map3.put(3, "C");
map3.put(4, "C");

System.out.println( new HashSet<>( map1.values() ).equals(new HashSet<>( map2.values() )) );       //true
System.out.println( new HashSet<>( map1.values() ).equals(new HashSet<>( map3.values() )) );       //true

Program output.

true
true

Drop me your questions related to comparing hashmaps in Java.

Happy Learning !!

Read More :

A Guide to Java HashMap
HashMap Java Docs

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Harish Lalwani

    March 8, 2020

    2.1 is returning true and true and it is correct.
    May be this article needs correction.

  2. Rohit

    July 27, 2019

    Looks like you copied 3.1 to 3.2 . I think you intended to use HashSet in 3.2 instead of ArrayList.

    • Lokesh Gupta

      July 28, 2019

      Thanks Rohit for pointing out. Corrected !!

  3. Danny

    May 14, 2019

    2.1 comparing the keysets results in true and true of course

  4. Sanjay

    January 8, 2019

    java program.

    The program displays student record of various universities
    First program needs to know how many universities records you wish to enter
    Secondly program takes the input for each university i.e student record for each of that university
    Thirdly program allows user to choose which universities record he wishes to display or filtering students w.r.t their majors(subject/department)

    hi lokesh. please solve this.

    • Lokesh Gupta

      January 8, 2019

      Please let me know what you tried so far?

Comments are closed on this article!

Search Tutorials

Java HashMap

  • HashMap – Introduction
  • HashMap – How it works
  • HashMap – Custom Key Design
  • HashMap – Synchronize HashMap
  • HashMap – Merge HashMaps
  • HashMap – Compare HashMaps
  • HashMap – Iterations
  • HashMap – Cloning

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces