Hello, World! What would be the easiest way to ge...
# stdlib
b
Hello, World! What would be the easiest way to get an "inverted" version of a Map (by that I mean the values become the keys and vice versa)?
t
What would you do with duplicate values? Would a
Map<K, V>
->
Map<V, List<K>>
?
b
very good point. Didn't think of it because in my case it's a 1-1 mapping.
t
tbh I thought there was a built in operator, but this will do the trick, albeit a bit untidily:
Copy code
map.entries
        .map { it.value to it.key }
        .groupBy { it.first }
        .mapValues { it.value.map { it.second } }
b
thanks! Isn't there a specific
.map
for Maps ? Something that takes a
(k: K1, v:V1) -> Pair<K2, V2>
and returns a
Map<K2, V2>
?
I recently tried to transform a
java.util.Properties
to a
Map<String, String>
and somehow this wasn't as trivial as I wanted, and I missed something like this
I mean it must be frequent to need to transform a map of something something to a map of something else something else 😛
n
mapOf("A" to 1, "B" to 2, "C" to 3).map { it.value to it.key }.toMap()
should work for 1:1 maps
n
mapOf(...).entries.associateBy({ it.value }) { it.key }
should also work for 1:1 maps
b
Thanks a lot! Very nice
b
You could add a little sugar to it by creating an extension function on the
Map
interface if this is functionality you find yourself requiring often 🙂
👍 3