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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)