What would be an idiomatic way to convert a `Map&l...
# stdlib
g
What would be an idiomatic way to convert a
Map<K, List<V>>
into a
Map<V, K>
such that every entry in the
List<V>
becomes associated with its original key
K
? (
{"foo": [1, 2, 3]}
becomes
{1: "foo", 2: "foo", 3: "foo"}
)
Currently I have:
Copy code
myMap.entries
  .flatMap { e ->
    e.value.map { it to e.key }
  }.toMap()
which I don't consider particularly intuitive
d
myMap.entries.fold(HashMap()) { m, (k, v) -> v.associateWithTo(m) { k } }
Something like that perhaps?
Probably doesn't compile but you get the drill
j
myMap.entries.map{(k,v)->v.map{it to k}}.toMap()
oh my bad missed the List<V> explicit param.