Thread
#stdlib
    gregorbg

    gregorbg

    2 years ago
    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:
    myMap.entries
      .flatMap { e ->
        e.value.map { it to e.key }
      }.toMap()
    which I don't consider particularly intuitive
    Dico

    Dico

    2 years ago
    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

    jimn

    2 years ago
    myMap.entries.map{(k,v)->v.map{it to k}}.toMap()
    oh my bad missed the List<V> explicit param.