The getOrDefault method in Java's Map interface provides a convenient way to retrieve a value for a given key. If the key is not present in the map, it returns a specified default value instead of null.

Example: Key Exists

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);

        int value = map.getOrDefault("A", 0); // Key exists
        System.out.println("Value for 'A': " + value); // Output: 10
    }
}

Example: Key Does Not Exist

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

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 10);
        map.put("B", 20);
        
        int value = map.getOrDefault("C", 0); // Key does not exist
        System.out.println("Value for 'C': " + value); // Output: 0
    }
}

Key Points:

  • Syntax: V getOrDefault(Object key, V defaultValue)

  • If the key exists, its associated value is returned.

  • If the key does not exist, the provided defaultValue is returned.

  • This method avoids null checks and simplifies code compared to using containsKey.

Considerations:

  • If the key exists but maps to null, null will be returned instead of the default value.

  • For expensive default values, consider using computeIfAbsent to avoid unnecessary computation.


Resources:​

1 -geeksforgeeks.org

2 -baeldung.com

3 -stackoverflow.com

← Back to Learning Journey