Gianfranco
05/27/2022, 4:37 PMMap<Key,
Set<Value>>
to Map<Value,
Key>
?araqnid
05/27/2022, 4:42 PMfun <Key, Value> Map<Key, Set<Value>>.invert(): Map<Value, Key> =
entries.flatMap { (k, vs) -> vs.map { it to k } }.toMap()
Gianfranco
05/27/2022, 5:00 PMKlitos Kyriacou
05/27/2022, 5:21 PMephemient
05/27/2022, 6:12 PMfun <K, V> Map<K, Iterable<V>>.invert(): Map<V, K> = buildMap {
for ((k, vs) in this@invert) {
for (v in vs) put(v, k)
}
}
just for fewer intermediary structures, but yes, this will result in losing duplicatesephemient
05/27/2022, 6:18 PMfun <K, V> Map<K, Iterable<V>>.invert(): Map<V, Set<K>> = entries.asSequence()
.flatMap { (k, vs) -> vs.asSequence().map(k::to) }
.groupingBy { it.second }
.fold(
initialValueSelector = { _, (k, _) -> mutableSetOf(k) },
operation = { _, set, (k, _) -> set.apply { add(k) } },
)
of course