Get Or Default

A lot of times situations arise where a key needs to be updated from a value from the map, and if not present then a default value must be assigned.

package org.wesome.java8;

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

class Apple {
    static String defaultValue = "value not present";

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");

        String value = map.get(4);
        if (Objects.isNull(value)) {
            value = defaultValue;
        }
        System.out.println("value = " + value);
    }
}

to avoid the if-else condition, Java 8 introduced the getOrDefault in Map Interface, it internally checks if the key has no value assigned then return the default value provided.

getOrDefault method will not modify the existing Map

The getOrDefault method will be available for all Map Intertface implementing concrete classes such as HashMap, LinkedHashMap and TreeMap ect

package org.wesome.java8;

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

class Apple {
    static String defaultValue = "value not present";

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");
        
        String value = map.getOrDefault(4, defaultValue);
        System.out.println("value = " + value);
    }
}

follow us on