Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform a Map by changing its values?

Tags:

kotlin

I need to hash all values in a map and return the same type of map.

My solution looks very wonky at the moment:

val hashedPolicies = policyProperties.map { it.key to it.value.hash() }.toMap()

Without the toMap(), it returns a List which is not acceptable.

Is there a better way of creating a new map of a map like this (without having to use .toMap())?

like image 662
Mr.Turtle Avatar asked Apr 09 '26 03:04

Mr.Turtle


1 Answers

Try mapValues:

inline fun <K, V, R> Map<out K, V>.mapValues(
    transform: (Entry<K, V>) -> R
): Map<K, R>

Returns a new map with entries having the keys of this map and the values obtained by applying the transform function to each entry in this Map.

The returned map preserves the entry iteration order of the original map.
kotlin-stdlib / kotlin.collections / mapValues

val test = mapOf("foo" to "bar")
println(test)
// {foo=bar}

val result = test.mapValues { it.value.hashCode() }
println(result)
// {foo=97299}
like image 80
Salem Avatar answered Apr 11 '26 14:04

Salem