Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

What is Hashmap in Java? Explained with Examples

Updated on 29 September, 2022

5.6K+ views
6 min read

HashMap is a collection class in Java. You can use it to store key and value pairs. Its performance depends on the initial capacity and the load factor. HashMap has various methods that allow you to use its hash table data structure. 

In the following article, we’ll explore what HashMap is and learn about its various constructors through examples. 

What is HashMap?

HashMap is a collection class based on Map. We use it to store Key & value pairs. You denote a HashMap Java as HashMap<K, V>, where K stands for Key and V stands for Value. 

HashMap is similar to the Hashtable class. The difference between the two is that HashMap is unsynchronized while Hashtable isn’t. Also, unlike Hashtable, HashMap allows null values and the null key. 

Since HashMap isn’t an ordered collection, it doesn’t return the keys and values in the order you insert them. Also, HashMap doesn’t sort the stored keys and values. If you want to use the HashMap class and its methods, you’ll have to import java.util.HashMap (or its superclass).

HashMap gives you a simple implementation of Java’s Map interface. You can access the key-value pairs you store through HashMap by using an index of another type (such as an integer). Keep in mind that if you use a duplicate key, it replaces the element of the relevant key. Also, you can only use one null key object; however, there can be any number of null values. 

HashMap implements Cloneable, Serializable, Map<K, V> interfaces. It extends the AbstractMap<K, V> class, and its direct subclasses are PrinterStateReasons and LinkedHashMap. 

Features of HashMap 

Following are the primary features in HashMap: 

  • It is a component of the java.util.package.
  • You can use duplicate values, but HashMap doesn’t allow duplicate keys. It means one key can’t have multiple values, but multiple keys can have a single value. 
  • You can use null keys only once, but you can use various null values. 
  • HashMap provides no guarantees regarding the map’s order. So, it doesn’t guarantee if the order will remain constant. 
  • HashMap is very similar to Hashtable, with the only difference being that HashMap is unsynchronized. 
  • HashMap implements a Serializable and Cloneable interface. 

HashMap Constructors

There are four constructors in HashMap:

1. HashMap()

HashMap() is the default constructor that creates an instance with a load factor of 0.75 and an initial capacity of 16.

Example

// Showing how HashMap() constructor works 

import java.io.*;
import java.util.*;
class AddElementsToHashMap {
    public static void main(String args[])
    {
        // You don’t have to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>();
        // Using Generics to initialize HashMap
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>();
        // Use the put method to add any element
        hm1.put(1, “A”);
        hm1.put(2, “B”);
        hm1.put(3, “C”);
        hm2.put(4, “D”);
        hm2.put(5, “E”);
        hm2.put(6, “F”);
        System.out.println(“Results of hm1 are : “
                           + hm1);
        System.out.println(“Results of HashMap hm2 are : “
                           + hm2);
    }
}
Output: 

Results of hm1 are : {1=A, 2=B, 3=C}

Results of hm2 are : {4=D, 5=E, 6=F}

2. HashMap(int initialCapacity)

HashMap(int initialCapacity) would create an instance with load 0.75 and a specific initial capacity. 

Example:

// Showing how HashMap(int initialCapacity) constructor works 

import java.io.*;

import java.util.*;

class AddElementsToHashMap {
    public static void main(String args[])
    {
        // You don’t have to mention the
        // Generic type twice
        HashMap<Integer, String> hm1 = new HashMap<>(10);
        // Using Generics to initialize HashMap
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(2);
        // Use the put method to add any element
        hm1.put(1, “A”);
        hm1.put(2, “B”);
        hm1.put(3, “C”);
        hm2.put(4, “D”);
        hm2.put(5, “E”);
        hm2.put(6, “F”);
        System.out.println(“Results of hm1 are : “
                           + hm1);
        System.out.println(“Results of HashMap hm2 are : “
                           + hm2);
    }
}
Output: 

Results of hm1 are : {1=A, 2=B, 3=C}

Results of hm2 are : {4=D, 5=E, 6=F}

3. HashMap(int initialCapacity, float loadFactor) 

HashMap(int initialCapacity, float loadFactor) generates an instance with a specific load factor and initial capacity.

Example:

// Showing how  HashMap(int initialCapacity, float loadFactor) Constructor works

import java.io.*;

import java.util.*;

class AddElementsToHashMap {
    public static void main(String args[])
    {
        // You don’t have to mention the
        // Generic type twice
        HashMap<Integer, String> hm1
            = new HashMap<>(5, 0.75f);
        // Using Generics to initialize the HashMap
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(3, 0.5f);
        // Use the put method to add elements
        hm1.put(1, “A”);
        hm1.put(2, “B”);
        hm1.put(3, “C”);
        hm2.put(4, “D”);
        hm2.put(5, “E”);
        hm2.put(6, “F”);
        System.out.println(“Results of hm1 are : “
                           + hm1);
        System.out.println(“Results of HashMap hm2 are : “
                           + hm2);
    }
}
Output: 

Results of hm1 are : {1=A, 2=B, 3=C}

Results of hm2 are : {4=D, 5=E, 6=F}

4. HashMap(Map map)

HashMap(Map map) would create an instance with the same mappings as the map you specify. 

Example:

// Showing how HashMap(Map map) constructor works 

import java.io.*;

import java.util.*;

class AddElementsToHashMap {
    public static void main(String args[])
    {
        // You don’t have to mention the
        // Generic type twice
        Map<Integer, String> hm1 = new HashMap<>();
         // Using Generics to initialize HashMap
        HashMap<Integer, String> hm2
            = new HashMap<Integer, String>(hml);
        // Use the put method to add any element
        hm1.put(1, “A”);
        hm1.put(2, “B”);
        hm1.put(3, “C”);
        hm2.put(4, “D”);
        hm2.put(5, “E”);
        hm2.put(6, “F”);
        System.out.println(“Results of hm1 are : “
                           + hm1);
        System.out.println(“Results of HashMap hm2 are : “
                           + hm2);
    }
}

Output

Results of hm1 are : {1=A, 2=B, 3=C}

Results of hm2 are : {4=D, 5=E, 6=F}

Learn more about Java

Java has many classes apart from HashMap. Learning about the nitty-gritty of each of those classes, their uses, and integration in Java by yourself is pretty challenging. The best way to go about this process is by taking a computer science course.

Taking a professional course will enable you to master the necessary skills and concepts through a structured curriculum. Furthermore, such courses offer an immersive learning experience facilitated by videos, live sessions, and online lectures that make it easier for you to understand theoretical fundamentals.

You can check out our Master of Science in Computer Science program offered in association with LJMU (Liverpool John Moores University, UK) and IIIT-B (International Institute of Information Technology, India). The course covers 500+ hours of content, 10+ live lectures, and 30+ case studies.

This 19-month course promises a highly value-oriented and global learning experience. The biggest value addition lies in the fact that you get to connect and engage with peers from across the world. upGrad boasts of having 40,000+ paid global learners spread in over 85+ countries.  As a result, you are exposed to new cultures, new opinions, and new perspectives that broaden your overall outlook. Not just that, you are trained by expert mentors from LJMU and IIIT-B who deliver dedicated and personalized assistance to help resolve your doubts. 

Along with these advantages, this program will provide you with 360 degrees career assistance that includes industry mentorship, networking opportunities, and much more. 

Conclusion

In this article, we learned what HashMap is, its different constructors, and how you can implement them through examples. HashMap has a ton of applications in Java – you can use HashMap to add items, remove them, and manage them as required. 

What are your thoughts on this guide on HashMap? Share them in the comment section below. 

RELATED PROGRAMS