Hello :wave: Is there a simple reverse transform o...
# getting-started
d
Hello 👋 Is there a simple reverse transform of a
Map<String, List<String>>
as in value elements become keys that map to the original keys? i.e. given
Copy code
val original = mapOf("a" to listOf("foo", "bar", "baz"), "b" to listOf("foo", "qux"))
I want to transform it to
Copy code
val transformed = mapOf("foo" to listOf("a", "b"), "bar" to listOf("a"), "baz" to listOf("a"), "qux" to listOf("b"))
anything "better" than
Copy code
original.entries.flatMap { entry -> entry.value.map { it to entry.key } }.groupBy(keySelector = { it.first }, valueTransform = { it.second })
h
Copy code
original.flatMap { (key, value) -> value.map { it to key } }
.groupBy({ it.first }, { it.second })
same as urs but looks nicer this way
a
I think yours is fine, but if you wanted an alternative, here’s mine:
Copy code
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.