HashMap keySet() Method Example

1. Introduction

The HashMap class in Java represents a collection that stores elements as key-value pairs, known as mappings. One of the fundamental methods provided by the HashMap class is the keySet() method. This method returns a Set view of the keys contained in the map. The returned set is backed by the map, meaning changes to the map are reflected in the set, and vice versa. The keySet() method is particularly useful for iterating over the keys of a HashMap, allowing for the performance of various operations such as searching, updating, and deleting elements based on their keys.

2. Program Steps

1. Create a HashMap and populate it with some key-value pairs.

2. Use the keySet() method to get a Set view of the keys in the HashMap.

3. Iterate over the set of keys and perform operations, such as retrieving values from the HashMap.

3. Code Program

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

public class HashMapKeySetExample {
    public static void main(String[] args) {
        // Step 1: Creating and populating a HashMap
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("Amit", 90);
        scores.put("Bina", 85);
        scores.put("Chetan", 95);
        scores.put("Disha", 88);

        // Step 2: Retrieving the set of keys from the HashMap
        Set<String> keys = scores.keySet();

        // Step 3: Iterating over the set of keys
        for (String key : keys) {
            // Retrieving each value from the HashMap by its key
            Integer value = scores.get(key);
            System.out.println(key + " scored " + value + " marks");


Amit scored 90 marks
Bina scored 85 marks
Chetan scored 95 marks
Disha scored 88 marks


1. A HashMap named scores is created to store the names of students as keys and their scores as values. This step demonstrates initializing a HashMap and populating it with key-value pairs.

2. The keySet() method is invoked on the HashMap, which returns a Set view of all the keys contained in the map. This set is stored in the variable keys.

3. The program then iterates over the set of keys using a for-each loop. During each iteration, it retrieves the value associated with the current key from the HashMap using the get() method. This demonstrates how to access and manipulate elements in a HashMap by iterating over its keys.