Increment a Map Value in Java 8

In this post, we will explore ways to increment a Map value in Java 8. If map contains the mapping for the specified key, the solution should increment its value by 1 else it should associate the value of 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 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. putIfAbsent()

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

 

Download   Run Code

Output:

{A=2, B=1}

 

2. merge()

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

 

Download   Run Code

Output:

{A=2, B=1}

 

3. getOrDefault()

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. computeIfPresent()

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

 

Download   Run Code

Output:

{A=2, B=1}

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 






Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
bitguru
Guest
bitguru