Mr.Turtle
Mr.Turtle

Reputation: 3090

How to transform a Map by changing its values?

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())?

Upvotes: 2

Views: 4547

Answers (2)

leonardkraemer
leonardkraemer

Reputation: 6813

Use fold to do everything in one go:

val hashedPolicies = policyProperties.entries.fold(mutableMapOf<KeyType, Int>{ map, it ->
    map.put(it.key, it.value.hashCode())
    map
}

While mapValues is more specific and suitable for this specific case, fold as less specific level method has the advantage to work on all iterable and array types. Also it allows you to use an arbitrary return type.

Upvotes: 0

Salem
Salem

Reputation: 14967

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}

Upvotes: 10

Related Questions