[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:


[Java 8] Map.compute example

Here’s a Java 8 Map.compute() example. Basically this construct replaces an idiom such as:

It does an in-place transformation by using a BiFunction, therefore you need to return if you have more than one statement. Another important thing about compute: If the BiFunction returns null and the key was in the map, it is…

Java CyclicBarrier example

An example from the very good Java 8 book “Beginning Java 8 Language Features”. :