View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
Java

Step by Step Java Tutorial Concepts - From Beginner to Pro

Learn Java programming from basics to advanced concepts with our comprehensive tutorials. Start from scratch and elevate your skills to expert level.

  • 192 Lessons
  • 32 Hours
right-top-arrow

Tutorial Playlist

191 Lessons
92

HashMap in Java

Updated on 28/03/20245,039 Views

Introduction

HashMap in Java is an integral part of the collections framework. It is located in the java.util package. It implements the Java Map interface in its most basic form. It saves the data as a key-value mapping, where each key corresponds to exactly one data type value. Here is a tutorial blog on how to use HashMap in Java.

Overview

This will cover the concepts of hierarchy in HashMap, different chrematistics of HashMap, constructors in HashMap, the internal structure of HashMap, advantages of HashMap, disadvantages of HashMap, and the basic usage of HashMap in Java, among others.

Methods in HashMap

Here are some of the HashMap methods in Java:

Method

Description

HashMap()

Constructs an empty HashMap.

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacities and the default load factor.

HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity and load factor.

clear()

Removes all key-value mappings from the HashMap.

clone()

Returns a shallow copy of the HashMap instance.

containsKey(Object key)

Returns true if the HashMap contains a mapping for the specified key.

containsValue(Object value)

Returns true if the HashMap contains at least one mapping with the specified value.

entrySet()

Returns a Set view of the key-value mappings in the HashMap.

get(Object key)

Returns the value to which the specified key is mapped or null if the key is not present in the HashMap.

isEmpty()

Returns true if the HashMap contains no key-value mappings.

keySet()

Returns a Set view of the keys in the HashMap.

put(K key, V value)

Associates the specified value with the specified key in the HashMap. If the key already exists, the previous value is replaced.

putAll(Map<? extends K, ? extends V> m)

Copies all of the mappings from the specified map to the HashMap.

remove(Object key)

Removes the mapping for the specified key from the HashMap if it is present.

size()

Returns the number of key-value mappings in the HashMap.

values()

Returns a Collection view of the values in the HashMap.

Methods Inherited From Class java.util.AbstractMap

Method

Description

equals()

Compares the specified object with the HashMap for equality.

hashCode()

Returns the hash code value for the HashMap.

toString()

Returns a string representation of the HashMap object.

Methods Inherited From Interface java.util.Map

Method

Description

equals()

Compares the specified object with the HashMap for equality.

hashCode()

Returns the hash code value for the HashMap.

Creating HashMap in Java: Example

import java.util.HashMap;
public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap
        HashMap<String, Integer> studentGrades = new HashMap<>();
// Add key-value pairs to the HashMap
        studentGrades.put("Alice", 95);
        studentGrades.put("Bob", 80);
        studentGrades.put("Charlie", 75);
        // Print the HashMap
        System.out.println(studentGrades);
    }
}

In this example, we create a new HashMap called studentGrades that maps String keys (student names) to Integer values (grades).

We use the put() method to add key-value pairs to the HashMap. In this case, we add three entries: "Alice" with a grade of 95, "Bob" with a grade of 80, and "Charlie" with a grade of 75.

Finally, we print the HashMap using System.out.println(), which displays the key-value pairs enclosed in curly braces.

Performing Various Operations on HashMap

Here is an example demonstrating various operations on a HashMap within a single program:

import java.util.HashMap;
public class HashMapOperationsExample {
    public static void main(String[] args) {
        // Create a new HashMap
        HashMap<String, Integer> studentGrades = new HashMap<>();
        // Add key-value pairs to the HashMap
        studentGrades.put("Alice", 95);
        studentGrades.put("Bob", 80);
        studentGrades.put("Charlie", 75);
        // Print the HashMap
        System.out.println("HashMap: " + studentGrades);
        // Get the value for a specific key
        int bobGrade = studentGrades.get("Bob");
        System.out.println("Bob's Grade: " + bobGrade);
        // Check if a key exists
        boolean hasCharlie = studentGrades.containsKey("Charlie");
        System.out.println("Does Charlie exist? " + hasCharlie);
        // Remove a key-value pair
        studentGrades.remove("Alice");
        // Check the size of the HashMap
        int size = studentGrades.size();
        System.out.println("Size of the HashMap: " + size);
        // Iterate over the HashMap
        System.out.println("Iterating over the HashMap:");
        for (String name : studentGrades.keySet()) {
            int grade = studentGrades.get(name);
            System.out.println(name + "'s Grade: " + grade);
        }
        // Update a value
        studentGrades.put("Bob", 90);
        int updatedBobGrade = studentGrades.get("Bob");
        System.out.println("Updated Bob's Grade: " + updatedBobGrade);
        // Clear the HashMap
        studentGrades.clear();
        // Check if the HashMap is empty
        boolean isEmpty = studentGrades.isEmpty();
        System.out.println("Is the HashMap empty? " + isEmpty);
    }
}

In this example, we perform various operations on a HashMap called studentGrades:

  • We create a new HashMap and add key-value pairs using the put() method.
  • We print the HashMap using System.out.println().
  • We retrieve the value for a specific key using the get() method.
  • We check if a key exists using the containsKey() method.
  • We remove a key-value pair using the remove() method.
  • We determine the size of the HashMap using the size() method.
  • We iterate over the HashMap using a for-each loop and keySet().
  • We update a value using the put() method.
  • We clear the HashMap using the clear() method.
  • We check if the HashMap is empty using the isEmpty() method.

Each operation is performed within the same program, showcasing different functionalities of a HashMap in Java.

Important Features of HashMap

The important features of HashMap in Java are:

  • Part of the java.util package.
  • Extends AbstractMap and implements Map interface.
  • Implements Cloneable and Serializable interfaces.
  • Uses hashing technique for efficient indexing and searching.
  • Does not allow duplicate keys but allows duplicate values.
  • Allows a null key (only once) and multiple null values.
  • Does not guarantee a specific order of elements.
  • Similar to HashTable but is unsynchronized.

These features make HashMap a versatile and widely used data structure in Java for efficiently storing and retrieving key-value pairs.

How Does HashMap Work Internally?

HashMap internally uses an array of nodes to store key-value pairs. Each node is an instance of an inner class in HashMap. The nodes are organized into buckets, and the number of buckets is called the capacity. The bucket in which a value is stored is determined by the key's hashCode() method.

When retrieving a value, the bucket is calculated using hashCode(), and then the equals() method is used to find the exact match within that bucket.

To avoid having too many buckets with multiple values, the capacity is doubled when 75% of the buckets become non-empty. The load factor triggers this resizing operation. The default load factor is 75%, and the initial capacity is 16, but both can be customized through the constructor.

This internal structure and resizing mechanism of HashMap enable efficient storage and retrieval of key-value pairs while dynamically adapting to the number of elements being stored.

Synchronized HashMap

To create a synchronized version of a HashMap in Java, you can use the Collections.synchronizedMap() method. Here's an example:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class main {
    public static void main(String[] args) {
        // Create a new HashMap
        Map<String, Integer> studentGrades = new HashMap<>();
        // Make the HashMap synchronized
        Map<String, Integer> synchronizedMap = Collections.synchronizedMap(studentGrades);
        // Add key-value pairs to the synchronized HashMap
        synchronizedMap.put("Alice", 95);
        synchronizedMap.put("Bob", 80);
        synchronizedMap.put("Charlie", 75);
        // Access values from the synchronized HashMap
        synchronized (synchronizedMap) {
            for (String name : synchronizedMap.keySet()) {
                int grade = synchronizedMap.get(name);
                System.out.println(name + "'s Grade: " + grade);
            }
        }
    }
}

In this example, we create a regular HashMap called studentGrades. Then, we use the Collections.synchronizedMap() method to create a synchronized version of the HashMap called synchronizedMap.

We add key-value pairs to the synchronized HashMap using the put() method, just like a regular HashMap.

We synchronize the code block using the synchronized keyword to ensure thread safety when accessing the synchronized HashMap. In this example, we synchronize on the synchronizedMap object.

Within the synchronized block, we iterate over the keys of the synchronized HashMap and retrieve the corresponding values.

Use Cases of HashMap

Here are some common use cases where HashMap can be applied effectively:

Phonebook: HashMap can be used to implement a phonebook. The names are stored as keys and corresponding phone numbers as values. This allows for efficient retrieval of phone numbers based on names.

Dictionary Application: HashMap is suitable for implementing a dictionary application. The words can be used as keys, and their meanings or descriptions can be stored as values. This enables fast lookup of word definitions based on the provided key (word).

Distributed Caching Systems: Distributed caching systems like Couchbase, Membase, and Redis are essentially extended versions of HashMaps. They provide high concurrency and large-scale data storage through replication and distribution. These systems allow for efficient caching and retrieval of frequently accessed data in distributed environments.

Advantages of HashMap

Here are the advantages of HashMap:

  • Fast retrieval: HashMap provides constant-time access to elements. This means the time to retrieve or insert elements remains constant, even as the size of the HashMap increases.
  • Efficient storage: HashMap uses a hashing function to map keys to indices in an underlying array, allowing a fast lookup of values based on keys. The hashing function distributes the entries across different buckets, ensuring efficient data storage and retrieval.
  • Flexibility: HashMap allows for storing null keys and values, offering flexibility in handling data. Additionally, HashMap can store key-value pairs of any data type. This provides versatility in its usage.
  • Easy to use: HashMap has a straightforward and user-friendly interface. This makes it easy to understand and implement in Java.

Disadvantages of HashMap

Here are the disadvantages of HashMap:

  • Unordered: HashMaps do not preserve the order of elements.
  • Not thread-safe: HashMaps are not inherently thread-safe.
  • Performance degradation: In certain situations, the performance of HashMap can degrade.
  • Complexity: The concept of hashing, collision resolution, and understanding the intricacies of the equals and hashCode methods can be challenging and complex.
  • Higher memory usage: HashMaps use an underlying array to store key-value pairs, which can result in higher memory usage than other data structures like arrays or lists.

Conclusion

This brief tutorial blog on HashMap will be beneficial for learners in understanding this Java concept better. Enrolling in a certified Java course can help you gain deeper insights into this programming language and understand HashMap better. You can consider courses at reputed online learning platforms such as upGrad.

FAQs

1.Can a HashMap contain duplicate values?

Yes, HashMap allows duplicate values. HashMap does not allow duplicate keys (keys must be unique). However, it is possible to have multiple entries with the same value.

2. How to print HashMap in Java?

You can print the HashMap in Java using System.out.println().

3. How does HashMap handle collisions?

HashMap handles collisions using a linked list at each bucket (array index) that stores entries with the same hash code but different keys. In HashMap in Java 8, if a bucket contains a certain number of entries (by default, 8), the linked list is converted into a balanced tree for improved performance.

Take the Free Java Quiz & See Your Rank!

image
right-top-arrowright-top-arrow
Need More Help? Talk to an Expert
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .