[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 removed. If it wasn’t nothing happens:

If the function returns null, the mapping is removed (or remains absent if initially absent).

And the output:

Check out the computeIfAbsent() method as well.

Leave a Reply

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