This post 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 a value equal to 1.

1. Checking for null

A simple solution is to check if the map contains the mapping for the specified key or not. If the mapping is not present, simply map the key with a value of 1; if the mapping is present, increment the key’s value by 1.

Download  Run Code

Output:

{A=101, B=1}

 
The above solution makes two calls to the put() method. We can avoid that by tweaking the solution a little, as demonstrated below:

Download  Run Code

Output:

{A=101, B=1}

2. Using containsKey() method

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

Download  Run Code

Output:

{A=101, B=1}

3. Using AtomicInteger or MutableInt class

We can also use AtomicInteger class 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}

That’s all about incrementing Map’s value in Java.

 
Must Read:

Increment a Map’s value in Java 8 and above