Denis Jung
Denis Jung

Reputation: 175

Kotlin - How to increase value of mutableMap

I wanna add 1 to a particular item value of mutableMap in Kotlin laguage. Below is what I made. Is there any way to make this code simple?

map[1] = map[1]?.let {it -> it + 1 } ?: 1

Upvotes: 2

Views: 584

Answers (3)

Adam Millerchip
Adam Millerchip

Reputation: 23091

I don't think there's a nice clean way of doing this, because we always have to handle the case that the key does not exist somehow.

You could use Map.merge() from the JDK. This will add a new key with value 1 if it doesn't already exist.

map.merge(1, 1, Int::plus)

That doesn't feel very idomatic though. So you could wrap it in an extention function:

fun MutableMap<Int, Int>.increment(key: Int) = merge(key, 1, Int::plus)

Example:

fun main() {
    val map = mutableMapOf(1 to 1)
    map.merge(1, 1, Int::plus)
    println(map)
    map.increment(1)
    println(map)
    map.increment(2)
    println(map)
}

Output:

{1=2}
{1=3}
{1=3, 2=1}

Upvotes: 0

gidds
gidds

Reputation: 18577

You could simplify that a little by doing the addition after handling the null:

map[1] = (map[1] ?: 0) + 1

If you're doing that a lot, you could add it as an extension function, e.g.:

fun <T> MutableMap<T, Int>.increment(key: T, defaultValue: Int = 0) {
    this[key] = (this[key] ?: defaultValue) + 1
}

(That version also lets you specify a different default value if you want.)

You could call that like:

map.increment(1)

You could extend that to add or subtract numbers other than 1.  (Though in that case, you'd probably want to change the function name.)

Upvotes: 1

Sash Sinha
Sash Sinha

Reputation: 22370

Maybe you could use getOrDefault:

fun main(args: Array<String>) {
    val map = mutableMapOf(1 to 0, 2 to 0)
    println("Before: " + map)
    map[1] = map.getOrDefault(1, 0) + 1
    println("After: " +  map)
}

Output:

Before: {1=0, 2=0}
After: {1=1, 2=0}

Upvotes: 3

Related Questions