This post will discuss several methods to increment the value of a map in Kotlin. If no key/value pair is found for the specified key, initialize the key with value 1.

1. Checking for null

The straightforward solution is to get the value for the specified key. If the key/value pair is present, increment the value by 1; otherwise, add the key with a value of 1.

Download Code

2. Using putIfAbsent() function

You can use the putIfAbsent() function to check if the key/value pair exists for the specified key or not. If not, you create the key/value pair of the specified key with the value 0. Finally, you increment the value by 1.

Download Code

3. Using getOrDefault() function

The getOrDefault() function returns the value of the specified key or the default value when no key/value pair exists for the given key. We can use this as:

Download Code

4. Using merge() function

You can also use the merge() function to increment the current value by the 1 with the remapping function.

Download Code

5. Using computeIfPresent() function

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

Download Code

6. Using containsKey() function

Another plausible way is to use the standard native function containsKey() to check if the map contains a key/value pair for a key or not.

Download Code

7. Using AtomicInteger class

You can also use getAndIncrement() or incrementAndGet() function from AtomicInteger class for incrementing the value.

Download Code

That’s all about incrementing the value of a map in Kotlin.