Iterate over map and create new map from key/value


#1

I want to iterate over the pairs in a map, and create a new map where the keys/values have been transformed. The “old school” code is:

val properties = ObjectMapper().readValue(fragment, Properties::class.java)
val newProperties = HashMap<String, String>()
for (property in properties) {
 newProperties.put(property.key.toString().replace(".", "_"), property.value.toString())
}

Is there an idiomatic way of doing this in Kotlin?


#2

Assuming properties is a Map:

val newProperties = properties.map { property ->
    property.key.toString().replace(".", "_") to property.toString()
 }.toMap()

#3

Or use instead of map(…).toMap() associate(…).


#4

Great, thank you!