Login

Sign Up

HashMap in Java
Tushar Varshney

Posted on Aug 1, 2025 | Coding

HashMap in Java

Introduction

HashMap in Java, HashMap in Java is a powerful data structure that stores data in key-value pairs, making it easy to access values quickly using their associated keys. It is a part of the Java Collections Framework and is widely used because of its fast performance. Behind the scenes, HashMap uses a technique called hashing, which converts keys into a unique hash code to locate their value efficiently. Unlike lists or arrays where you access data by index, in HashMap you access data by a unique key, just like looking up a word in a dictionary. It doesn’t allow duplicate keys and can store one null key and multiple null values. Overall, HashMap is ideal when you need to store and retrieve data quickly based on unique identifiers.

List of Content

  • What is HashMap?
  • Why use HashMap?
  • Key Features of HashMap
  • How HashMap Works Internally
  • Creating and Initializing a HashMap
  • Common Operations in HashMap
  • Important Methods in HashMap
  • Null Keys and Null Values in HashMap
  • Iterating Through a HashMap
  • Example with Dry run:
  • Conclusion

πŸ” What is HashMap?

HashMap is a part of Java’s Collection Framework that allows you to store and manage data in the form of key-value pairs. It is like a digital dictionary where each unique key maps to a specific value. If you know the key, you can instantly get the valueβ€”no need to search through the entire data.

πŸ€” Why Use HashMap?

  • Fast access to data using keys (average time complexity: O(1)).
  • Stores data as key-value pairs, making lookups easy and efficient.
  • No duplicate keys allowed, ensuring unique data mapping.
  • Supports null values and one null key.
  • Useful in scenarios like caching, configurations, and lookup tables.

🌟 Key Features of HashMap:

  1. Implements the Map<K, V> interface.
  2. No duplicate keys allowed.
  3. HashMap permits one null key and as many null values as needed.
  4. Does not maintain insertion order.
  5. For most operations like adding, removing, and fetching data, HashMap offers constant time complexity β€” O(1) on average.
  6. ashMap is not synchronized, which means it is not safe to use in multithreaded programs unless externally synchronized (e.g., using Collections.synchronizedMap()).
  7. HashMap is a built-in class in Java found in java.util and implements the Map interface.

βš™οΈ How HashMap Works Internally:

  1. Internally, a HashMap uses an array of buckets. Each bucket is essentially a slot where entries (key-value pairs) can be stored. These buckets hold nodes, which are instances of an internal class like Node<K, V>.

  2. Hashing the Key:

    • Java first calculates the hash code of the key using its hashCode() method.

    • This hash code is then processed to find the index (bucket number) in the array where the entry should go.

        index = hashCode(key) % numberOfBuckets
    
    
  3. Handling Collisions:

    • Before Java 8: It used a Linked List to store multiple entries in the same bucket.

    • Since Java 8: If the number of items in a bucket exceeds a threshold (usually 8), it converts the linked list into a Balanced Tree (Red-Black Tree) for faster lookup.

  4. Resizing (Rehashing):
    If the number of entries grows beyond a certain point (based on load factor, default is 0.75), the HashMap automatically increases the array size (usually doubles it) and reassigns all the existing entries to the new buckets. This is called rehashing.

    HashMap<String, Integer> map = new HashMap<>();
    map.put("Apple", 10);
    
    

πŸ›  Creating ans Initializing a HashMap:

import java.util.HashMap;

public class Example {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Banana", 20);
        map.put("Orange", 15);
        System.out.println(map);
    }
}

You can also initialize using Map.of() (Java 9+):

Map<String, Integer> map = Map.of("A", 1, "B", 2);


πŸ”„ Comman Operations in HashMap:

Operation Method Example
Add element map.put("Key", value);
Remove element map.remove("Key");
Get value map.get("Key");
Check key map.containsKey("Key");
Size map.size();
Clear all map.clear();

1. Add Elements:

map.put("Apple", 10);
map.put("Banana", 20);

2. Get Value by Key:

int value = map.get("Apple");  // returns 10

3. Remove an Entry:

map.remove("Banana");

4. Check if Key Exists:

map.containsKey("Apple");  // returns true

5. Check if Value Exists:

map.containsValue(10);  // returns true

6. Get Size of Map:

int size = map.size();  // e.g., 1 or 2

7. Clear All Entries:

map.clear();  // Removes all key-value pairs


πŸ“š Important methods in HashMap:

  • Adds values using put()
  • Retrieves a value using get()
  • Checks for keys/values using containsKey() and containsValue()
  • Removes an item with remove()
  • Displays all keys using keySet()
  • Displays all values using values()
  • Iterates over all entries using entrySet()

Example :

import java.util.*;

public class HashMapMethodsDemo {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<String, String> map = new HashMap<>();

        // put() - Add entries
        map.put("Name", "Alice");
        map.put("City", "Delhi");
        map.put("Language", "Java");

        // get() - Retrieve value by key
        System.out.println("Name: " + map.get("Name"));  // Alice

        // containsKey() - Check if a key exists
        System.out.println("Contains key 'City'? " + map.containsKey("City"));  // true

        // containsValue() - Check if a value exists
        System.out.println("Contains value 'Java'? " + map.containsValue("Java"));  // true

        // remove() - Remove an entry
        map.remove("City");
        System.out.println("After removing 'City': " + map);

        // keySet() - Get all keys
        System.out.println("All keys: " + map.keySet());

        // values() - Get all values
        System.out.println("All values: " + map.values());

        // entrySet() - Get all key-value pairs
        System.out.println("Key-Value Pairs:");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }
    }
}


🟑 Null Keys and Null values in HashMap:

  • HashMap allows one null key.
  • It permits multiple null values.
map.put(null, 100);
map.put("Test", null);

Internally, null key is stored at bucket 0 using a special mechanism to avoid calling hashCode().


πŸ” Iterating Through HashMap:

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

Other ways:

* Using keySet() or values()
* Java 8’s forEach() with Lambda:
map.forEach((k, v) -> System.out.println(k + ":" + v));


Let's Take an Example with dry run:

import java.util.*;

public class HashMapDemo {
    public static void main(String[] args) {
        // Step 1: Create a HashMap
        HashMap<String, Integer> marks = new HashMap<>();

        // Step 2: put() - Add entries
        marks.put("Alice", 85);
        marks.put("Bob", 90);
        marks.put("Charlie", 75);
        marks.put("David", 90);  // duplicate value is allowed

        // Step 3: get() - Get a value
        System.out.println("Bob's Marks: " + marks.get("Bob"));  // 90

        // Step 4: containsKey() and containsValue()
        System.out.println("Contains key 'Alice'? " + marks.containsKey("Alice"));  // true
        System.out.println("Contains value 100? " + marks.containsValue(100));      // false

        // Step 5: remove() - Remove a key
        marks.remove("Charlie");
        System.out.println("After removing 'Charlie': " + marks);

        // Step 6: size() - Total entries
        System.out.println("Total students: " + marks.size());

        // Step 7: keySet() - All keys
        System.out.println("Student Names: " + marks.keySet());

        // Step 8: values() - All values
        System.out.println("All Marks: " + marks.values());

        // Step 9: entrySet() - All key-value pairs
        System.out.println("All Entries:");
        for (Map.Entry<String, Integer> entry : marks.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // Step 10: clear() - Remove all entries
        marks.clear();
        System.out.println("After clearing map: " + marks);
    }
}

πŸ” Dry Run: Step-by-Step Execution:

marks.put("Alice", 85);
marks.put("Bob", 90);
marks.put("Charlie", 75);
marks.put("David", 90);

Internal HashMap state (simplified):

Key Value
Alice 85
Bob 90
Charlie 75
David 90

Operation-wise Dry Run:

  • get("Bob") β†’ Finds and prints 90

  • containsKey("Alice") β†’ true

  • containsValue(100) β†’ false

  • remove("Charlie") β†’ Deletes the "Charlie" entry

  • size() β†’ Now the size is 3

  • keySet() β†’ [Alice, Bob, David]

  • values() β†’ [85, 90, 90]

  • entrySet() β†’

    Alice -> 85
    Bob -> 90
    David -> 90
    
    
  • clear() β†’ HashMap becomes empty {}


βœ… CONCLUSION:

HashMap is a core data structure every Java developer should master. With its efficient performance, support for nulls, and easy-to-use methods, it’s a powerful choice for managing key-value data. Understanding its internal working and limitations helps in writing better and more optimized code.

Happy Learning! πŸš€

πŸ‘‰ For more blogs and topics, Click Here.

3 Reactions

0 Bookmarks

Read next

Tushar Varshney

Tushar Varshney

Jan 6, 25

5 min read

|

Problem on Bubble Sort

Tushar Varshney

Tushar Varshney

Jan 8, 25

6 min read

|

Problem on Selection sort