HashMap getOrDefault() Method Example

1. Introduction

The HashMap in Java is part of the Collections Framework, providing a basic implementation of the Map interface. It stores data in key-value pairs, allowing efficient data retrieval by key. One useful method in the HashMap class is getOrDefault(Object key, V defaultValue). This method retrieves the value mapped by a specific key. If the key does not exist, it returns a default value specified by the programmer. This feature is particularly helpful in avoiding NullPointerException and simplifies the need for additional checks for the presence of a key.

2. Program Steps

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

2. Demonstrate fetching a value for an existing key using getOrDefault.

3. Demonstrate fetching a value for a non-existing key, specifying a default value.

4. Show practical use cases of getOrDefault in handling data processing tasks.

3. Code Program

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

public class HashMapGetOrDefaultExample {
    public static void main(String[] args) {
        // Step 1: Creating and populating a HashMap
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 90);
        scores.put("Bob", 95);
        scores.put("Charlie", 85);

        // Step 2: Fetching a value for an existing key
        int aliceScore = scores.getOrDefault("Alice", 0);
        System.out.println("Alice's score: " + aliceScore);

        // Step 3: Fetching a value for a non-existing key
        int daveScore = scores.getOrDefault("Dave", 0);
        System.out.println("Dave's score (default): " + daveScore);

        // Practical use-cases
        // Handling missing entries without if-checks
        String searchKey = "Eve";
        int score = scores.getOrDefault(searchKey, -1);
        System.out.println(searchKey + "'s score (with default for missing): " + score);

        // Accumulating values while avoiding NullPointerException
        scores.put("Eve", scores.getOrDefault("Eve", 0) + 5);
        System.out.println("Updated scores: " + scores);
    }
}

Output:

Alice's score: 90
Dave's score (default): 0
Eve's score (with default for missing): -1
Updated scores: {Alice=90, Bob=95, Charlie=85, Eve=5}

Explanation:

1. The program begins by creating a HashMap named scores and populating it with scores of three students: Alice, Bob, and Charlie. The map holds student names as keys and their scores as values.

2. To fetch Alice's score, getOrDefault is used with "Alice" as the key and 0 as the default value. Since "Alice" exists in the map, her actual score of 90 is returned.

3. When attempting to fetch Dave's score, who is not present in the map, getOrDefault returns the specified default value of 0, thus avoiding a null return value or additional checks.

4. The program also showcases practical use cases, such as handling missing entries gracefully without if-checks by returning a default value for missing keys and safely accumulating values for keys that might not initially exist in the map.

5. The getOrDefault method significantly simplifies code by providing a default value when keys are missing, enhancing code readability and safety against NullPointerException.

Comments