HashMap in Java: A Complete Guide

HashMap in Java is a powerful key-value data structure used for fast retrieval and efficient updates. This tutorial covers its internal mechanics, essential operations, iteration methods, and performance considerations, making it a valuable tool for applications like caching, indexing, and frequency counting.

Data Structures & Algorithm using Java

HashMap is a prominent key-value data structure in Java that supports efficient updates, along with fast retrieval, insertion, and deletion capabilities. The java.util package provides HashMap as an efficient lookup tool, making it suitable for applications such as caching, database indexing, and frequency counting.

In this tutorial, we’ll deep dive into HashMap, covering its definition, internal workings, key operations, iteration techniques, and performance optimizations.

What is HashMap in Java?

A HashMap is a part of Java’s Map interface that stores data in key-value pairs. It uses hashing to map keys to values, making retrieval operations very fast (average time complexity of O(1)).

Key Features of HashMap

  • Allows null keys and multiple null values.
  • Unordered – the insertion order is not maintained.
  • Allows unique keys; duplicate keys overwrite previous values.
  • Non-thread-safe (use ConcurrentHashMap for thread safety).

While HashMap is a key-value store, you may also want to learn about HashSet in Java, which is a set-based collection in Java that utilizes hashing.

How HashMap Works Internally

Internally, HashMap in Java uses an array of linked lists (known as a bucket array). The key’s hash code determines which bucket it will be placed into. If multiple keys produce the same hash code (collision), Java resolves it using separate chaining (linked list) or red-black tree (Java 8+ for large buckets).

Steps Involved in HashMap Operations:

  1. The hashCode() method generates a unique integer (hash) for a given key.
  2. The hash is used to compute an index in the internal bucket array.
  3. If the index is empty, a new key-value pair is inserted. If not, Java handles collisions using chaining (linked list or tree structure).
  4. When a key is retrieved, equals() is used to match the exact key.

Creating a HashMap in Java (Syntax & Example)

To create a HashMap, we use the following syntax:

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        // Creating a HashMap
        HashMap<String, Integer> studentMarks = new HashMap<>();

        // Adding key-value pairs
        studentMarks.put("Alice", 85);
        studentMarks.put("Bob", 92);
        studentMarks.put("Charlie", 78);

        // Retrieving a value
        System.out.println("Alice's Marks: " + studentMarks.get("Alice"));

        // Checking if a key exists
        System.out.println("Is Bob in the HashMap? " + studentMarks.containsKey("Bob"));

        // Removing an entry
        studentMarks.remove("Charlie");

        // Printing the final HashMap
        System.out.println("Final HashMap: " + studentMarks);
    }
}

Important HashMap Methods and Operations

Here are some essential operations on HashMap:

MethodDescriptionExample
put(K key, V value)Inserts a key-value pair.map.put("John", 25);
get(Object key)Retrieves a value using a key.map.get("John");
remove(Object key)Removes a key-value pair.map.remove("John");
containsKey(Object key)Checks if a key exists.map.containsKey("John");
containsValue(Object value)Checks if a value exists.map.containsValue(25);
size()Returns the number of key-value pairs.map.size();
isEmpty()Checks if the map is empty.map.isEmpty();

Java collections like HashMap often work hand-in-hand with other interfaces, such as the Queue Interface, for managing elements in specific orders

Iterating Over a HashMap

There are multiple ways to iterate over a HashMap:

1. Using for-each loop (Entry Set)

for (Map.Entry<String, Integer> entry : studentMarks.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

2. Using keySet() (Iterate Over Keys)

for (String key : studentMarks.keySet()) {
    System.out.println("Key: " + key);
}

3. Using values() (Iterate Over Values)

for (Integer value : studentMarks.values()) {
    System.out.println("Value: " + value);
}

4. Using forEach() (Lambda Expression)

studentMarks.forEach((key, value) -> System.out.println(key + " : " + value));

The use of lambda expressions in HashMap operations can be better understood through Functional Interfaces and Lambda Expressions in Java.

HashMap vs Other Map Implementations

FeatureHashMapTreeMapLinkedHashMap
OrderingNo orderingSorted by keyInsertion order maintained
PerformanceO(1) for get()O(log n) for get()O(1) for get()
Null Keys1 allowedNot allowed1 allowed

Performance and Use Cases

  • Time Complexity:
    • Average: O(1) for put(), get(), and remove().
    • Worst case: O(n) (when all elements fall in the same bucket).

  • Use Cases:
    • Caching (quick lookups).
    • Counting word frequencies in text analysis.
    • Implementing LRU (Least Recently Used) Cache.

Common Mistakes and Best Practices

Mistakes

  1. Using mutable keys – If keys are mutable, their hashCode() may change, making them untraceable.
  2. Not handling null keys/values properly – Be cautious when dealing with null keys and values.
  3. Ignoring initial capacity and load factor – Setting a proper capacity avoids frequent rehashing.

Best Practices

  1. Use ConcurrentHashMap in multi-threaded environments.
  2. Choose the right initial capacity to minimize rehashing.
  3. Override equals() and hashCode() correctly for custom objects.

Frequently Asked Questions

1. Why is HashMap not thread-safe?

HashMap is not synchronized, meaning multiple threads modifying it simultaneously may lead to race conditions and data inconsistency. Use ConcurrentHashMap for thread-safe operations.

You can learn more about handling concurrency in Java through Threads in Java.

2. What happens if two keys have the same hash code?

If two keys generate the same hash, they are stored in the same bucket using separate chaining (linked list or tree structure in Java 8+). The equals() method then determines the correct key-value pair.

3. What is the default capacity and load factor of HashMap?

By default, HashMap has a capacity of 16 and a load factor of 0.75. This means resizing occurs when 75% of the capacity is filled.

4. Can we store a null key in HashMap?

Yes, HashMap allows one null key and multiple null values. However, Hashtable does not allow null keys or values.

5. How does HashMap resize itself?

When the number of elements exceeds capacity * loadFactor , the size doubles, and all entries are rehashed into a new bucket array. This process is costly, so setting an optimal initial capacity is recommended.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top