Kotlin Map: Transform Both Key and Value

Oct 21, 2019
Combine mapKeys and mapValues
val data = mapOf(    1 to "Desmond",    2 to "Mei Ru")val newData = data.entries.associate { (key, value) ->    key to value}// or - performance of associate and associateBy should be equalval newData = data.entries.associateBy({(key, value) ->    value}, {(key, value) ->    key})// or - less efficientval newData = data.map { (key, value) ->    value to key}.toMap()

Transform key only

val newData = data.mapKeys { (key, value) ->    key - 1}

Transform values only

val newData = data.mapValues { (key, value) ->    value.toUpperCase()}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.