Iterate over map and create new map from key/value

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?

Assuming properties is a Map:

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

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

Great, thank you!