When attempting to retrieve a value from a Map which doesn’t exist, often it is desirable for the Map to provide an initial value. This saves the developer adding in extra logic to detect, create and insert the initial value. Java 8 adds a new Map method…
java.util.Map::computeIfAbsent(K key, Function mappingFunction) has the following properties:
- The second argument takes a function, which is called when there is no value for the key. The function is called to construct, insert and return the new value.
- If a new value is constructed, this is performed atomically, so that the function will only ever be used at most once for each key
This method is particularly useful when used in a concurrent context i.e.
java.util.concurrent.ConcurrentHashMap::computeIfAbsent. Before this method was available it was necessary to provide external synchronization, to ensure that overwrite problems didn’t occur. The following tutorial shows presents
Step through computeIfAbsent in action
Click on the flashing arrow, to step through Codelytics’ visualization of computeIfAbsent.
Do you like this Codelytics’ visualization?
If you like our visualizations, be sure to subscribe to our mailing list below.
Do you like how this tutorial is presented?
The objective of this tutorial is to communicate Java concepts effectively, if you have any suggestions on how this could be improved or aspects you liked; leave a comment.