https://kotlinlang.org logo
#announcements
Title
# announcements
j

Joffrey

12/06/2019, 10:50 AM
Hi guys, is there a stdlib function to create a
Map<K, List<V>>
from a
List<Pair<K,V>>
? I'm looking for the same thing as
toMap()
, but instead of discarding duplicate keys, it would aggregate the values in a list. For now, I haven't found shorter than this trivial
groupBy
:
Copy code
fun <K, V> List<Pair<K, V>>.toMapAggregate(): Map<K, List<V>> = groupBy(
    { (k, _) -> k },
    { (_, v) -> v }
)
k

karelpeeters

12/06/2019, 10:51 AM
val map = list.groupBy({ it.first }, { it.second })
Ah my bad you knew that already.
👍 1
j

Joffrey

12/06/2019, 10:51 AM
Yes, but it is a bit shorter, so that's a win already 🙂 I was hoping for a stdlib function that would do that on its own, because it seems like a very common use case to me.
4 Views