Java HashMap – Key-Value Pairs
100%

Java HashMap

A HashMap is a class in the Java Collections Framework that stores data in key-value pairs. Each key must be unique, while values can be duplicated. HashMap is useful when you want to retrieve a value using its associated key.

1. Introduction to HashMap

Consider this student information:

Student ID (Key) Student Name (Value)
101Rahul
102Amit
103Priya

We can use student IDs as keys and student names as values. A HashMap allows us to find a name by providing its ID.

import java.util.HashMap;

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

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

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

Output:

Amit

2. Creating a HashMap

Import the HashMap class from the java.util package.

import java.util.HashMap;

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

Examples of generic types:

  • Integer, String: numeric keys and text values.
  • String, Integer: text keys and numeric values.
  • String, String: text keys and text values.
Remember: HashMap uses wrapper classes such as Integer instead of primitive types such as int.

3. Adding Elements Using put()

The put(key, value) method adds a key-value pair to a HashMap.

import java.util.HashMap;

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

        marks.put("Rahul", 85);
        marks.put("Amit", 90);
        marks.put("Priya", 95);

        System.out.println(marks);
    }
}

Example output:

{Rahul=85, Amit=90, Priya=95}

HashMap does not guarantee iteration order, so the actual output order may differ.

4. Accessing Values Using get()

Use get(key) to retrieve the value associated with a key.

import java.util.HashMap;

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

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

        System.out.println(students.get(101));
        System.out.println(students.get(103));
        System.out.println(students.get(999));
    }
}

Output:

Rahul
Priya
null

If a key is not present, get() returns null.

5. Updating Values in HashMap

Adding a value using an existing key replaces that key's previous value.

import java.util.HashMap;

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

        marks.put("Rahul", 70);
        marks.put("Amit", 80);

        marks.put("Rahul", 95);

        System.out.println(marks.get("Rahul"));
    }
}

Output:

95

Rahul's marks change from 70 to 95. The map still has only two keys.

6. Removing Elements Using remove()

The remove(key) method removes the entry associated with a key.

import java.util.HashMap;

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

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

        students.remove(102);

        System.out.println(students);
    }
}

Example output:

{101=Rahul, 103=Priya}

The entry with key 102 is removed. The remaining entries are still stored in the map.

7. Checking Keys and Values

HashMap provides methods to check whether keys or values exist.

import java.util.HashMap;

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

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

        System.out.println(students.containsKey(101));
        System.out.println(students.containsKey(105));
        System.out.println(students.containsValue("Amit"));
    }
}

Output:

true
false
true
  • containsKey() checks for a key.
  • containsValue() checks for a value.

8. Getting the Size of a HashMap

The size() method returns the number of key-value mappings in a HashMap.

import java.util.HashMap;

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

        products.put("Pen", 10);
        products.put("Book", 50);
        products.put("Bag", 500);

        System.out.println("Total products: " + products.size());
    }
}

Output:

Total products: 3

9. Looping Through a HashMap

Use entrySet() and a for-each loop to access every key-value pair.

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

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

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

        for (Map.Entry<Integer, String> entry
                : students.entrySet()) {

            System.out.println(
                entry.getKey() + " : " + entry.getValue()
            );
        }
    }
}

Possible output:

101 : Rahul
102 : Amit
103 : Priya

The displayed order is not guaranteed. Each entry provides its key through getKey() and its value through getValue().

10. Getting All Keys and Values

Use keySet() to access all keys and values() to access all values.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> countries = new HashMap<>();

        countries.put("India", "New Delhi");
        countries.put("Japan", "Tokyo");
        countries.put("France", "Paris");

        System.out.println("Countries:");

        for (String country : countries.keySet()) {
            System.out.println(country);
        }

        System.out.println("Capitals:");

        for (String capital : countries.values()) {
            System.out.println(capital);
        }
    }
}

Both loops display their results in an unspecified order because HashMap does not guarantee ordering.

11. Useful HashMap Methods

Method Purpose
put(key, value) Adds or updates an entry.
get(key) Returns the value for a key.
remove(key) Removes an entry by key.
containsKey(key) Checks whether a key exists.
containsValue(value) Checks whether a value exists.
size() Returns the number of entries.
isEmpty() Checks whether the map is empty.
keySet() Returns a set of keys.
values() Returns a collection of values.
clear() Removes all entries.
getOrDefault(key, defaultValue) Returns a default value when the key is absent.

Example of getOrDefault():

int marks = scores.getOrDefault("Neha", 0);

If the map does not contain the key Neha, the variable receives 0. This call does not insert Neha into the map.

12. Practical Example – Student Marks

This example stores student names and marks, displays the marks for a particular student, and checks whether a student exists.

import java.util.HashMap;

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

        marks.put("Rahul", 85);
        marks.put("Amit", 78);
        marks.put("Priya", 92);

        String student = "Priya";

        if (marks.containsKey(student)) {
            System.out.println(
                student + "'s marks: " + marks.get(student)
            );
        } else {
            System.out.println("Student not found.");
        }

        marks.put("Amit", 88);

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

Output:

Priya's marks: 92
Updated Amit marks: 88

13. Practice Assignments

  1. Create a HashMap to store five student IDs and names.
  2. Create a HashMap to store product names and prices.
  3. Retrieve a value using its key.
  4. Update a student's marks using put().
  5. Remove an entry using remove().
  6. Check whether a particular key exists.
  7. Display the total number of entries using size().
  8. Display all key-value pairs using entrySet().
  9. Display all keys using keySet().
  10. Use getOrDefault() to return a default value for a missing key.

🧠 Quick Quiz

1. Which method adds or updates a key-value pair in HashMap?




2. What does get() return when a key is not present?




3. Which method checks whether a key exists?