HashMap entrySet() Method Example

1. Introduction

The HashMap class in Java is a part of the Collections Framework, designed to store elements in key-value pairs, making data access highly efficient. The entrySet() method is a key feature of the HashMap class, returning a Set view of the mappings contained in the map. Each element in this set is a Map.Entry object, which allows you to work with the map's entries directly. This method is particularly useful for iterating over a HashMap, enabling access to both the key and the value of each entry.

2. Program Steps

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

2. Retrieve the entry set from the HashMap using the entrySet() method.

3. Iterate over the entry set and print each key-value pair.

3. Code Program

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

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

        // Step 2: Retrieving the entry set from the HashMap
        Set<Map.Entry<String, Integer>> entries = students.entrySet();

        // Step 3: Iterating over the entry set and printing each entry
        for (Map.Entry<String, Integer> entry : entries) {
            System.out.println(entry.getKey() + " scored " + entry.getValue() + " marks");
        }
    }
}

Output:

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

Explanation:

1. A HashMap named students is created, mapping String objects (student names) to Integer values (marks). This step demonstrates how to initialize a HashMap and populate it with data.

2. The entrySet() method is used to retrieve a Set view of the mappings contained in the HashMap. This set contains Map.Entry objects, where each Map.Entry represents a key-value mapping in the map.

3. The program iterates over the set of entries using an enhanced for loop. For each Map.Entry object in the set, the key (student name) and value (marks) are retrieved using getKey() and getValue() methods, respectively. These values are then printed to the console, demonstrating how to access and work with individual entries in a HashMap through its entry set.

Comments