How do I use Map.getOrDefault() default method in Java?

The Map.getOrDefault(Object key, V defaultValue) method in Java 8 is a convenience default method to return the value for a given key. If the map does not contain a mapping for the key, then it returns the default value.

This method can be particularly useful in situations where you’re working with a map and need to fetch a value for a key, but aren’t sure if the key exists in the map. It helps you handle these scenarios without a need to write extra conditional code to check if the key is present (i.e., using containsKey(Object key)) before trying to get the value.

Here’s a common use case without getOrDefault():

Map<String, Integer> map = new HashMap<>();
// fill map...

Integer value;
if (map.containsKey("key")) {
    value = map.get("key");
} else {
    value = -1;
}

Here’s a basic example of how to use getOrDefault():

package org.kodejava.util;

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

public class MapGetOrDefaultExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // Get a value of the key "A". It will return value 1 as
        // "A" is present in the map.
        Integer value = map.getOrDefault("A", -1);
        System.out.println("Value: " + value);

        // Try to get a value of the key "Z". As "Z" is not present
        // in the map, it will return the default value -1.
        value = map.getOrDefault("Z", -1);
        System.out.println("Value: " + value);
    }
}

In this example, “Value: 1” and then “Value: -1” will be printed in the console. In the first case, the key “A” is in the map, so the associated value 1 is returned. In the second case, the key “Z” does not exist in the map, so the default value of -1 is returned.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.