I think yours is fine, but if you wanted an alternative, here’s mine:
fun main() {
val transformed = remapValuesToKeys(original)
println(transformed) // {foo=[a, b], bar=[a], baz=[a], qux=[b]}
}
val original: Map<String, List<String>> = mapOf("a" to listOf("foo", "bar", "baz"), "b" to listOf("foo", "qux"))
fun remapValuesToKeys(
original: Map<String, List<String>>
): Map<String, List<String>> {
return buildMap<String, MutableList<String>> {
for ((k, values) in original) {
for (value in values) {
val newValues = getOrPut(value, ::mutableListOf)
newValues += k
}
}
}
}
https://pl.kotl.in/gaW-Mnh7w
It’s more traditional, as it uses traditional for-loops instead of collection functions, which some might find easier to work with.