Java map.get(key) - automatically do put(key) and return if key doesn't exist?

Sridhar Sarnobat picture Sridhar Sarnobat · Nov 30, 2011 · Viewed 57.6k times · Source

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.

I'm sure something somewhere exists to avoid this, but my Googling efforts yielded nothing relevant. Any suggestions?

Answer

Roger Lindsjö picture Roger Lindsjö · Nov 30, 2011

The

java.util.concurrent.ConcurrentMap 

and from Java 8

Java.util.Map

has

putIfAbsent(K key, V value) 

which returns the value mapped to key or inserts the given value and null if no value is mapped for the key.

If you need lazy evaluation of the value there is

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