Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconWhat is Hashmap in Java? Explained with Examples

What is Hashmap in Java? Explained with Examples

Last updated:
2nd Jul, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
What is Hashmap in Java? Explained with Examples

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. 

Ads of upGrad blog

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. 

Ads of upGrad blog

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. 

Profile

Arjun Mathur

Blog Author
Arjun is Program marketing manager at UpGrad for the Software development program. Prior to UpGrad, he was a part of the French ride-sharing unicorn "BlaBlaCar" in India. He is a B.Tech in Computers Science from IIT Delhi and loves writing about technology.
Get Free Consultation

Selectcaret down icon
Select Area of interestcaret down icon
Select Work Experiencecaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6198
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas &#038; Topics
13303
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions &#038; Answers [For Freshers &#038; Experienced]
5775
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions &#038; Answers in US [2024]
5425
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas &#038; Topics For Beginners [US 2023]
11429
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5488
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5614
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5058
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5565
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon