Chapter 55 of 77

HashMap in Java

Sometimes we don't just want to store values. We also want to store a value along with some identifier that helps us find it.

For example, suppose we want to store the marks of students. Instead of remembering that John's marks are at index 0 and Jason's marks are at index 1, we can directly associate each student's name with their marks.

For this, Java provides HashMap.

A HashMap stores data in key-value pairs.

You can think of it like this:

John  → 85
Jason → 92
Alex  → 78

Here, the student's name is the key, and the marks are the value.

Creating a HashMap

HashMap is part of the java.util package, so we first import it:

import java.util.HashMap;

Then we can create a HashMap:

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

Here:

  • String is the type of the key.

  • Integer is the type of the value.

So this map will store a String as the key and an Integer as the value.

Adding Data

We use the put() method to add key-value pairs.

marks.put("John", 85);
marks.put("Jason", 92);
marks.put("Alex", 78);

Now our map contains:

John  → 85
Jason → 92
Alex  → 78

Each student name acts as a key that helps us find the corresponding mark.

Getting a Value

We can use the get() method to retrieve a value using its key.

System.out.println(marks.get("John"));

Output:

85

Similarly:

System.out.println(marks.get("Jason"));

Output:

92

This is one of the biggest advantages of a HashMap. Instead of remembering an index, we can use a meaningful key to find the value.

If the key does not exist, get() returns null. To get a fallback value instead, use getOrDefault():

System.out.println(marks.get("Alex"));
System.out.println(marks.getOrDefault("Alex", 0));

If "Alex" has not been added yet, the output is:

null
0

Keys Must Be Unique

A HashMap cannot have duplicate keys.

For example:

marks.put("John", 85);
marks.put("John", 95);

The second put() doesn't create another "John" entry. Instead, it replaces the old value.

The map now contains:

John → 95

So you can remember:

Keys are unique, but values can be duplicated.

For example, this is perfectly valid:

marks.put("John", 85);
marks.put("Jason", 85);

Both students can have the same mark because the values don't have to be unique.

Changing a Value

We can use put() to update an existing value.

marks.put("John", 90);

If "John" already exists, its old value is replaced.

So:

Before:
John → 85

After:
John → 90

Removing a Key-Value Pair

We can remove an entry using the remove() method:

marks.remove("John");

This removes the key "John" and its associated value.

We can also clear the entire map:

marks.clear();

After clear(), the map will be empty.

Checking Whether a Key Exists

We can use containsKey() to check whether a particular key exists.

System.out.println(marks.containsKey("John"));

If "John" exists, the result is:

true

If it doesn't exist:

false

We can also check whether a particular value exists using containsValue():

System.out.println(marks.containsValue(85));

Finding the Number of Entries

We can use size() to find how many key-value pairs are currently stored.

System.out.println(marks.size());

For example, if we have:

John  → 85
Jason → 92
Alex  → 78

the size is:

3

Looping Through a HashMap

We often need to process every key-value pair in a HashMap.

One common way is using entrySet():

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

For this example, we need to import Map as well:

import java.util.HashMap;
import java.util.Map;

The output could look like:

John → 85
Jason → 92
Alex → 78

The exact iteration order of a HashMap is not guaranteed, so you should not depend on the entries appearing in a particular order.

Getting Only Keys

If we only want the keys, we can use keySet():

for (String name : marks.keySet()) {
    System.out.println(name);
}

This will go through the student names.

Getting Only Values

If we only want the values, we can use values():

for (Integer mark : marks.values()) {
    System.out.println(mark);
}

This will go through the marks.

A Real-World Example

Imagine you're building a simple product system.

Each product has a unique product ID, and we want to associate that ID with the product name.

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

products.put(101, "Laptop");
products.put(102, "Keyboard");
products.put(103, "Mouse");

Now we can quickly find a product using its ID:

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

Output:

Keyboard

Here:

Key   → Product ID
Value → Product Name

This key-value structure is useful in many real applications.

Counting Frequencies

One of the most common uses of a HashMap in coding interviews is counting how many times each item appears:

String[] words = {"apple", "banana", "apple", "cherry", "apple", "banana"};

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

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

System.out.println(count.get("apple"));
System.out.println(count.get("banana"));
System.out.println(count.get("cherry"));

Output:

3
2
1

The same thing can also be written as count.merge(word, 1, Integer::sum);, which you will see in more advanced code.

How Fast Is a HashMap?

A HashMap uses the key's hashCode() to decide where to store each entry, and equals() to compare keys. Because of this, put(), get(), remove() and containsKey() take O(1) time on average. (containsValue() is O(n), because it has to check every value.)

A few more facts that are often asked in interviews:

  • A HashMap allows one null key and any number of null values.

  • If you use objects of your own class as keys, that class must override both equals() and hashCode().

  • If you need insertion order, use LinkedHashMap. If you need keys in sorted order, use TreeMap.

  • HashMap is not thread-safe. For multithreaded code, use ConcurrentHashMap.

HashMap vs ArrayList

It's useful to understand when you'd choose a HashMap instead of an ArrayList.

An ArrayList stores values using indexes:

0 → John
1 → Jason
2 → Alex

A HashMap stores values using keys:

John → 85
Jason → 92
Alex → 78

Use an ArrayList when you mainly need an ordered collection of elements and want to access them by position.

Use a HashMap when you want to associate one piece of information with another and retrieve values using a key.

A Complete Example

Let's create a small student marks program:

import java.util.HashMap;

class Main {
    public static void main(String[] args) {

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

        marks.put("John", 85);
        marks.put("Jason", 92);
        marks.put("Alex", 78);

        System.out.println("John's marks: " + marks.get("John"));

        marks.put("John", 90);

        System.out.println("Updated marks: " + marks.get("John"));
    }
}

Output:

John's marks: 85
Updated marks: 90

The main thing to remember is:

HashMap stores data as key-value pairs, where each key is unique and is used to find its corresponding value.

For example:

Student Name → Marks
John         → 85
Jason        → 92
Alex         → 78

Once you understand the idea of key → value, HashMap becomes much easier to work with.