Map.computeIfAbsent

If the specified key is not already associated with a value (or is mapped to {@code null}), attempts to compute its value using the given mapping function and enters it into this map unless {@code null}.

<p>If the function returns {@code null} no mapping is recorded. If the function itself throws an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most common usage is to construct a new object serving as an initial mapped value or memoized result, as in:

<pre> {@code map.computeIfAbsent(key, k -> new Value(f(k))); }</pre>

<p>Or to implement a multi-value map, {@code Map<K,Collection!V>}, supporting multiple values per key:

<pre> {@code map.computeIfAbsent(key, k -> new HashSet!V()).add(v); }</pre>

More...
interface Map(K, V)
final
V
computeIfAbsent
(
K key
,
Function!(K, V) mappingFunction
)

Detailed Description

@implSpec The final implementation is equivalent to the following steps for this {@code map}, then returning the current value or {@code null} if now absent:

<pre> {@code if (map.get(key) is null) { V newValue = mappingFunction.apply(key); if (newValue !is null) map.put(key, newValue); } }</pre>

<p>The final implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties. In particular, all implementations of subinterface {@link hunt.concurrency.ConcurrentMap} must document whether the function is applied once atomically only if the value is not present.

@param key key with which the specified value is to be associated @param mappingFunction the function to compute a value @return the current (existing or computed) value associated with the specified key, or null if the computed value is null @throws NullPointerException if the specified key is null and this map does not support null keys, or the mappingFunction is null @throws UnsupportedOperationException if the {@code put} operation is not supported by this map (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>) @throws ClassCastException if the class of the specified key or value prevents it from being stored in this map (<a href="{@docRoot}/java/util/Collection.html#optional-restrictions">optional</a>)

Meta