How to Increment a key’s value of a Map in Java

In this post, we will discuss several methods to increment a key’s value of a Map in Java. If no mapping is present for the specified key in the Map, map the key to value equal to 1.

 

1. Checking for Null

Simple solution is to check if the map contains mapping for the specified key or not. If the mapping is not present, then we simply map the key with value of 1, else if the mapping is present, we increment the key’s value by 1.

 

Download   Run Code

Output:

{A=101, B=1}

Above solution makes two calls to the put() function. We can avoid that by tweaking the solution a little as demonstrated below:

 

Download   Run Code

Output:

{A=101, B=1}

 

2. containsKey() method

This approach is also similar to the previous method but uses containsKey() method to check if the map contains a mapping for a key or not.

 

Download   Run Code

Output:

{A=101, B=1}

 

 

3. AtomicInteger or MutableInt

We can also use AtomicInteger and call getAndIncrement() or incrementAndGet() method to increment the value as shown below. Another alternative could be to use MutableInt class which provides increment() method.

 

Download   Run Code

Output:

{A=101, B=1}

 

 
Must Read: How to Increment a Map Value in Java 8

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of