Attempts to compute a mapping for the specified key and its current
mapped value (or null if there is no current mapping). For
example, to either create or append a String msg to a value
mapping:
map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
(Method merge() is often simpler to use for such purposes.)
If the function returns null, the mapping is removed (or
remains absent if initially absent). If the function itself throws an
(unchecked) exception, the exception is rethrown, and the current mapping
is left unchanged.
key | key with which the specified value is to be associated | |
remappingFunction | the function to compute a value |
NullPointerException | if the specified key is null and this map does not support null keys, or the remappingFunction is null | |
UnsupportedOperationException | if the put operation
is not supported by this map
(optional) | |
ClassCastException | if the class of the specified key or value prevents it from being stored in this map (optional) |
@implSpec
The default implementation is equivalent to performing the following
steps for this map, then returning the current value or
null if absent:
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (oldValue != null ) {
if (newValue != null)
map.put(key, newValue);
else
map.remove(key);
else {
if (newValue != null)
map.put(key, newValue);
else
return null;
}
}
The default 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 java.util.concurrent.ConcurrentMap must document
whether the function is applied once atomically only if the value is not
present.
Diagram: Map Simple