Java HashMap

Introduction

The Java HashMap class is one of the most widely used implementations of the Map interface in the Java Collections Framework. It stores data in the form of key-value pairs, where each key is unique and is associated with a single value. HashMap is known for its high performance, making it the preferred choice for applications that require fast insertion, retrieval, and deletion of data.

The HashMap class belongs to the java.util package and internally uses a hash table to store entries. When a key-value pair is added, Java calculates the hash code of the key and determines the appropriate bucket for storing the entry. This mechanism allows most operations such as put(), get(), and remove() to execute in constant time (O(1)) on average.

HashMap allows one null key and multiple null values, making it flexible for various programming scenarios.

What is Java HashMap?

A HashMap is a collection that stores data as key-value pairs.

  • Each key must be unique.
  • Multiple keys can have the same value.
  • If an existing key is inserted again, the old value is replaced with the new one.
Key Value
101 Rahul
102 Amit
103 Neha

Here:

  • Keys: 101, 102, 103
  • Values: Rahul, Amit, Neha

A HashMap provides quick access to values using their corresponding keys.

Java HashMap Hierarchy


Object
   │
AbstractMap
   │
HashMap

The HashMap class implements the following interfaces:

  • Map
  • Cloneable
  • Serializable

Features of Java HashMap

Some important features of HashMap are:

  • Stores data as key-value pairs
  • Keys are unique
  • Allows duplicate values
  • Allows one null key
  • Allows multiple null values
  • Does not maintain insertion order
  • Uses a hash table internally
  • Dynamic size
  • Supports Generics
  • Fast average-case performance

Syntax

Import Statement


import java.util.HashMap;

or


import java.util.*;

Creating a HashMap


HasMap<Integer, String> students = new HashMap<>();

Using the Map interface:


Map<Integer, String> students = new HashMap<>();

Programming to the Map interface is considered a best practice because it improves flexibility.

Constructors of HashMap

1. Default Constructor


Map<Integer, String> map = new HashMap<>();

Creates an empty HashMap with the default initial capacity (16) and load factor (0.75).

2. Constructor with Initial Capacity


Map<Integer, String> map = new HashMap<>(20);

Creates a HashMap with an initial capacity of 20.

3. Constructor with Capacity and Load Factor


Map<Integer, String> map = new HashMap<>(20,0.75f);
  • Initial Capacity = 20
  • Load Factor = 0.75

The load factor determines when the HashMap should resize.

4. Constructor from Another Map


Map<Integer, String> map1 = new HashMap<>();
map1.put(101, "Rahul");
map1.put(102, "Amit");
HasMap<Integer, String> map2 = new HashMap<>(map1);
System.out.println(map2);

Output

{101=Rahul, 102=Amit}

Common Methods of HashMap

Method Description
get() Returns the value associated with a key
remove() Removes a key-value pair
containsKey() Checks if a key exists
containsValue() Checks if a value exists
size() Returns the number of key-value pairs
isEmpty() Checks whether the map is empty
clear() Removes all mappings
keySet() Returns all keys
values() Returns all values
entrySet() Returns all key-value pairs

Example 1: Creating a HashMap


import java.util.*;
public class HashMapExample {
    public static void main(String[] args) {
      Map<Integer, String> students = new HashMap<>();
        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");

        System.out.println(students);
    }
}

Output

{101=Rahul, 102=Amit, 103=Neha}

The order of entries may vary because HashMap does not preserve insertion order.

Example 2: Retrieving a Value


import java.util.*;
public class GetExample {
    public static void main(String[] args) {
        Map<Integer, String> students = new HashMap<>();
        students.put(101, "Rahul");
        System.out.println(students.get(101));
    }
}

Output

Rahul

Example 3: Updating a Value


import java.util.*;

public class UpdateExample {

    public static void main(String[] args) {

       Map<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");

        students.put(101, "Rohan");

        System.out.println(students);
    }
}

Output

{101=Rohan}

The value is updated because duplicate keys are not allowed.

Example 4: Removing an Entry


import java.util.*;

public class RemoveExample {

    public static void main(String[] args) {

        HasMap<Integer, String> students = new HashMap<>();

        students.put(101, "Rahul");
        students.put(102, "Amit");

        students.remove(102);

        System.out.println(students);
    }
}

Output

{101=Rahul}

Example 5: Iterating Through a HashMap


import java.util.*;
public class LoopExample {
    public static void main(String[] args) {
      HasMap<Integer, String> students = new HashMap<>();
        students.put(101, "Rahul");
        students.put(102, "Amit");
        students.put(103, "Neha");
        for (Map.Entry entry : students.entrySet()) {
            System.out.println(entry.getKey()
                    + " : "
                    + entry.getValue());
        }
    }
}

Output

101 : Rahul 102 : Amit 103 : Neha

How HashMap Works Internally

HashMap internally uses a hash table consisting of buckets.

The process of storing a key-value pair is:

  1. The key’s hashCode() method is called.
  2. Java calculates the bucket index using the hash code.
  3. The entry is stored in that bucket.
  4. If multiple keys map to the same bucket (a collision), Java stores them using a linked list or a balanced tree (for large numbers of collisions in modern Java versions).
  5. During retrieval, Java calculates the hash again and quickly locates the correct bucket.

This design provides very fast average-case performance.

HashMap vs LinkedHashMap vs TreeMap

Feature HashMap LinkedHashMap TreeMap
Duplicate Keys No No No
Duplicate Values Yes Yes Yes
Insertion Order No Yes No
Sorted Keys No No Yes
Null Key One One No
Null Values Yes Yes Yes
Internal Structure Hash Table Hash Table + Linked List Red-Black Tree
Performance Fastest Fast Slower

Time Complexity

Operation Time Complexity
put() O(1) Average
remove() O(1) Average
containsKey() O(1) Average
containsValue() O(n)

In rare cases with many collisions, performance may degrade, but modern Java versions optimize this using balanced trees.

Real-life Example

Imagine you’re building an online shopping application.

Each product has a unique product ID:

Product ID Product Name
1001 Laptop
1002 Mouse
1003 Keyboard

Using a HashMap:


products.put(1001, "Laptop");
products.put(1002, "Mouse");
products.put(1003, "Keyboard");

To retrieve the product:


System.out.println(products.get(1002));

Output:

Mouse

Other real-world applications include:

  • Student record management
  • Employee databases
  • User authentication
  • Configuration settings
  • Inventory systems
  • Shopping carts
  • API response caching
  • Session management

Advantages of Java HashMap

  • Fast insertion, retrieval, and deletion
  • Stores key-value pairs efficiently
  • Allows one null key and multiple null values
  • Dynamic resizing
  • Supports Generics
  • Widely used in Java applications
  • Flexible and easy to use
  • Suitable for large datasets

Limitations of Java HashMap

  • Does not maintain insertion order
  • Does not sort keys
  • Duplicate keys are not allowed
  • Not synchronized
  • Performance depends on proper implementation of hashCode() and equals() for custom keys

Common Mistakes

1. Expecting Duplicate Keys


map.put(101, "Rahul");
map.put(101, "Amit");

Output:

{101=Amit}

The second value replaces the first.

2. Assuming HashMap Maintains Order

Incorrect assumption:


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

The output order is not guaranteed.

Use LinkedHashMap if insertion order is important.

3. Using get() Without Checking for Null


System.out.println(map.get(999));

If the key doesn’t exist, null is returned.

Safer approach:


if(map.containsKey(999)){
    System.out.println(map.get(999));
}

4. Forgetting Generics

Incorrect:


System.out.println(map.get(999));

Correct:


HasMap<Integer, String> Map = new HashMap<>();

5. Ignoring equals() and hashCode() in Custom Keys

When using custom objects as keys, always override both equals() and hashCode() to ensure correct key comparison and retrieval.

Best Practices

  • Declare variables using the Map interface.

Map<Integer, String> Students = new HashMap<>();
  • Use HashMap when ordering is not required.
  • Use LinkedHashMap for insertion-order iteration.
  • Use TreeMap when sorted keys are needed.
  • Always use Generics for type safety.
  • Check for missing keys with containsKey() when appropriate.
  • Override equals() and hashCode() for custom key classes.

Conclusion

The Java HashMap class is one of the most efficient and widely used data structures for storing key-value pairs. Its hash table implementation provides excellent average-case performance for inserting, retrieving, and removing data, making it the preferred choice for many real-world Java applications.

Although HashMap does not maintain insertion order or sort its keys, its speed and flexibility make it ideal for scenarios where fast access is more important than ordering.

Java HashMap – Interview Questions

Q 1: What is HashMap in Java?
Ans: HashMap stores data in key-value pairs.
Q 2: Does HashMap allow duplicate keys?
Ans: No, duplicate keys are not allowed.
Q 3: Can HashMap have null values?
Ans: Yes, one null key and multiple null values.
Q 4: Is HashMap synchronized?
Ans: No, it is not thread-safe.
Q 5: Which package contains HashMap?
Ans: java.util

Java HashMap – Objective Questions (MCQs)

Q1. Which package contains the HashMap class in Java?






Q2. Which of the following is true about HashMap in Java?






Q3. Which method is used to insert a key-value pair into a HashMap?






Q4. What will happen if you try to insert a duplicate key in a HashMap?






Q5. Which method is used to retrieve a value associated with a key in a HashMap?