Java HashMap


In Java, a HashMap is one of the most widely used data structures in the Collection Framework. It stores data in the form of key-value pairs, allowing fast access to values using their unique keys. It is an excellent choice when you need to store, retrieve, or update data efficiently based on keys rather than indexes.

What is a HashMap in Java?

A HashMap is a class in java.util package that implements the Map interface. It uses a hashing technique to store and retrieve data quickly. Each entry in a HashMap consists of a key and a value, where the key must be unique, but values can be duplicated.

Unlike lists or arrays, a HashMap does not maintain insertion order. Instead, it arranges entries based on the hash code of keys. This makes it extremely fast for lookups, insertions, and deletions.

Syntax:

HashMap<KeyType, ValueType> map = new HashMap<>();

For example:

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

Here, Integer is the key type, and String is the value type.

How HashMap Works

Internally, a HashMap uses a technique called hashing. When you insert a key-value pair, the key’s hash code is calculated, and the data is stored in a “bucket” corresponding to that hash value.

If two keys produce the same hash code (called a collision), HashMap uses a linked list or balanced tree to handle it efficiently.

When you retrieve data, Java recalculates the hash code of the key and directly accesses the bucket, which makes the search very fast — usually constant time, O(1).

Creating and Adding Elements to a HashMap

Let’s look at how to create and add items to a HashMap.

import java.util.*;

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

        students.put(101, "Anita");
        students.put(102, "Meera");
        students.put(103, "Kavya");

        System.out.println(students);
    }
}

Output:

{101=Anita, 102=Meera, 103=Kavya}

Here, put() is used to add elements. Each student ID acts as a key, and the name is the value.

Accessing Elements from a HashMap

You can access elements in a HashMap using the get() method.

System.out.println(students.get(102));

Output:

Meera

If you try to access a key that doesn’t exist, Java returns null.

Updating and Removing Elements

You can update a value using the same key or remove an entry using remove().

students.put(102, "Priya"); // updates the value for key 102
students.remove(101); // removes key 101 and its value

System.out.println(students);

Output:

{102=Priya, 103=Kavya}

Iterating Through a HashMap

You can iterate through a HashMap in different ways:

Using for-each loop

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

Using keySet()

for (Integer id : students.keySet()) {
    System.out.println("ID: " + id);
}

Using values()

for (String name : students.values()) {
    System.out.println("Name: " + name);
}

Checking for Keys and Values

You can check if a key or value exists using:

students.containsKey(103); // returns true
students.containsValue("Kavya"); // returns true

This is helpful when you want to avoid overwriting data accidentally.

Example: Counting Word Frequency Using HashMap

A HashMap is often used for counting occurrences or managing grouped data.

import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        String text = "apple banana apple mango banana apple";
        String[] words = text.split(" ");

        HashMap<String, Integer> wordCount = new HashMap<>();

        for (String word : words) {
            wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
        }

        System.out.println(wordCount);
    }
}

Output:

{apple=3, banana=2, mango=1}

This program uses getOrDefault() to simplify counting — if a word doesn’t exist, it starts with 0.

Important Methods in HashMap

Method Description
put(key, value) Adds a new key-value pair
get(key) Returns value for the key
remove(key) Removes entry with given key
containsKey(key) Checks if a key exists
containsValue(value) Checks if a value exists
size() Returns number of elements
clear() Removes all entries

Key Points About HashMap

  • Keys are unique; values can be duplicated.

  • HashMap allows one null key and multiple null values.

  • It is not synchronized, meaning multiple threads cannot modify it safely at once.

  • If you need a thread-safe version, use Collections.synchronizedMap() or ConcurrentHashMap.

  • It does not maintain insertion order (use LinkedHashMap if order matters).

Real-Life Use Cases of HashMap

HashMaps are extremely versatile and commonly used in:

  • Storing and retrieving configuration data

  • Caching user sessions

  • Counting frequencies of items

  • Managing key-value-based data like user IDs, phone numbers, etc.

  • Fast lookups in backend systems

Summary of the Tutorial

A HashMap in Java is a powerful collection that stores key-value pairs for fast and flexible data management. It allows constant-time access and modification, making it ideal for applications that require quick lookups. By understanding methods like put(), get(), and iteration techniques, you can easily manage complex datasets with clarity and speed.


Practice Questions

  1. Create a Java program to store student roll numbers and names using a HashMap, then display all entries.

  2. Write a Java program that adds five country-capital pairs in a HashMap and prints each pair using a for-each loop.

  3. Create a program to check if a specific key and value exist in a HashMap.

  4. Write a program to update an existing value in a HashMap and display the updated map.

  5. Create a program that removes a key-value pair from a HashMap and prints the remaining entries.

  6. Write a program to count the frequency of each character in a given string using a HashMap.

  7. Create a program to find the size of a HashMap and clear all elements.

  8. Write a Java program that merges two HashMaps into a single one.

  9. Create a program that uses getOrDefault() to safely access a key that may not exist.

  10. Write a program to iterate over keys, values, and entries of a HashMap and print them separately.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top