javadictionarygetnull

Java map.get(key) - Is there a way to automatically call put(key) and return if the key doesn't exist?


I am sick of the following pattern:

value = map.get(key);
if (value == null) {
    value = new Object();
    map.put(key, value);
}

This example only scratches the surface of the extra code to be written when you have nested maps to represent a multi-dimensional structure.

Is there some Java method to avoid this?


Solution

  • The

    java.util.concurrent.ConcurrentMap 
    

    and from Java 8

    Java.util.Map
    

    has

    putIfAbsent(K key, V value) 
    

    which returns the existing value, and if that is null inserts given value. So if no value exists for key returns null and inserts the given value, otherwise returns existing value

    If you need lazy evaluation of the value there is

    computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)