Kotlin Map transform example – mapTo, map Keys or Values

In this tutorial, I will show you many examples that transform a Kotlin Map using map, mapTo, mapKeys, mapKeysTo, mapValues, mapValuesTo.

Related Posts:
Kotlin HashMap tutorial with examples
Kotlin List & Mutable List tutorial with examples


Kotlin transform Map to List

We can easily transform a Kotlin Map to List using map() method. It will return a new List with elements transformed from entries in original Map.

var bzkMap: Map<Int, String> = mapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var bzkList = bzkMap.map { it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[0-zero, 1-one, 2-two, 3-three]

Sometimes the transformation could produce null, so we filter out the nulls by using the mapNotNull() function instead of map()

var bzkList = bzkMap.mapNotNull { if (it.key == 0) null else it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[1-one, 2-two, 3-three]

You can also use mapTo() and mapNotNullTo() with a destination as input pamameter.

var bzkList = mutableListOf<String>()

bzkMap.mapTo(bzkList) { it.key.toString() + '-' + it.value }
println(bzkList)

bzkList.clear()

bzkMap.mapNotNullTo(bzkList) { if (it.key == 0) null else it.key.toString() + '-' + it.value }
println(bzkList)

Output:

[0-zero, 1-one, 2-two, 3-three]
[1-one, 2-two, 3-three]

Kotlin transform Map keys

The example shows you how to transform Map keys in Kotlin using:

var bzkMap: Map<Int, String> = mapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var keysMap = bzkMap.mapKeys { it.key * 100 }
println(keysMap)

var newKeysMap = mutableMapOf<Int, String>()

bzkMap.mapKeysTo(newKeysMap) { it.key * 1000 }
println(newKeysMap)

Output:

{0=zero, 100=one, 200=two, 300=three}
{0=zero, 1000=one, 2000=two, 3000=three}

Kotlin transform Map values

The example shows you how to transform Map values in Kotlin using:

var bzkMap: Map<Int, String> = mapOf(0 to "zero", 1 to "one", 2 to "two", 3 to "three")

var valuesMap = bzkMap.mapValues { it.value.toUpperCase() }
println(valuesMap)

var newValuesMap = mutableMapOf<Int, String>()

bzkMap.mapValuesTo(newValuesMap) { '-' + it.value.toUpperCase() + '-' }
println(newValuesMap)

Output:

{0=ZERO, 1=ONE, 2=TWO, 3=THREE}
{0=-ZERO-, 1=-ONE-, 2=-TWO-, 3=-THREE-}

Further Reading