https://kotlinlang.org logo
#getting-started
Title
# getting-started
n

nkiesel

07/12/2022, 6:58 AM
given a map with possibly repeated values, is the following best way to reverse it (to a Map<V, List<K>>)
Copy code
fun <K, V> Map<K, V>.reverse(): Map<V, List<K>> = entries.groupBy { it.value }.map { it.key to it.value.map { it.key } }.toMap()
d

Dan Fingal-Surma

07/12/2022, 7:10 AM
entries.groupBy({ it.value }, { it.key })
👌 1
n

nkiesel

07/12/2022, 7:15 AM
Nice, thanks!
k

Klitos Kyriacou

07/12/2022, 8:28 AM
btw I think the right terminology is "invert".
2 Views