Chapter 45 of 57

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.

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.

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.