This post will explore ways to increment a map value in Java 8 and above. If the map contains the mapping for the specified key, the solution should increment its value by 1; otherwise, it should associate 1 with the specified key.

In the previous post, we have seen how to increment a key’s value of a map in Java 7 or less. This post covers a bunch of useful methods introduced in the Map interface with Java 8, such as putIfAbsent(), merge(), getOrDefault() and computeIfPresent(), which can be used to increment a map value.

1. Using putIfAbsent() method

The putIfAbsent() method associates the specified key with the given value if it is not already associated with a value. We can use this method to check if a mapping exists for the specified key or not. If not, we create the mapping of the specified key with the value 0. Finally, we increment the key’s value by 1.

Download  Run Code

Output:

{A=2, B=1}

2. Using merge() method

We can also use the merge() method, where the remapping method increments the existing value by the specified value of 1.

Download  Run Code

Output:

{A=2, B=1}

3. Using getOrDefault() method

The getOrDefault() method returns the value of the specified key or returns the specified default value if no mapping exists for the key in the map. We can make use of this method, as demonstrated below:

Download  Run Code

Output:

{A=2, B=1}

4. Using computeIfPresent() method

The computeIfPresent() returns null if no value is associated with the specified key; otherwise, it computes a new mapping given the key and its existing value.

Download  Run Code

Output:

{A=2, B=1}

That’s all about incrementing a Map Value in Java.