Home > Mobile >  Kotlin Map and Compute Functions
Kotlin Map and Compute Functions

Time:01-21

I am trying to re-compute values for all entries in a mutable map without changing the keys.

Here is the code (with comments showing what I am expecting)

fun main(args: Array<String>) {

    var exampleMap: MutableMap<Int, String> = mutableMapOf(1 to "One", 2 to "Two")

    // Before it's {1-"One", 2-"Two"}
    with(exampleMap) {
        compute(k){
            _,v -> k.toString   "__"   v
        }
    }

    // Expecting {1->"1__One", 2->"2__Two"}


 }

I don't want to use mapValues because it creates a copy of the original map. I think compute is what I need, but I am struggling to write this function. Or, rather I don't know how to write this. I know the equivalent in Java (as I am a Java person) and it would be:

map.entrySet().stream().forEach(e-> map.compute(e.getKey(),(k,v)->(k "__" v)));

How can I achieve that in Kotlin with compute ?

Regards,

CodePudding user response:

The best way to do this is by iterating over the map's entries. This ensures you avoid any potential concurrent modification issues that might arise due to modifying the map while iterating over it.

map.entries.forEach { entry ->
    entry.setValue("${entry.key}__${entry.value}")
}

CodePudding user response:

Use onEach function:

var exampleMap: MutableMap<Int, String> = mutableMapOf(1 to "One", 2 to "Two")
println(exampleMap)
exampleMap.onEach {
   exampleMap[it.key] = "${it.key}__${it.value}"     
}
println(exampleMap)

Output:

{1=One, 2=Two}
{1=1__One, 2=2__Two}

onEach performs the given action on each element and returns the list/array/map itself afterwards.

  • Related