[Java 8] Map.computeIfAbsent()

The computeIfAbsent method is similar to compute(), however it only has side effects on the map if the key wasn’t there before applying the method.

One important thing is that the signature takes a Function as an argument and not a BiFunction as in the case of compute().

Here’s an example:

 

The result:

As always with all these new compute methods:

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 ConcurrentMap must document whether the function is applied once atomically only if the value is not present.

Leave a Reply

Your email address will not be published. Required fields are marked *