vrfrom07
vrfrom07

Reputation: 59

Kotlin - Building a map of lists from a flat list in pragmatic way

I have a Kotlin flat list made of objects, something like...

    data class Someone(var name: String, var age: Int)

    val someoneList = listOf<Someone>(Someone("Joe", 12), Someone("Bill", 15), Someone("Nancy", 12))

...and I'd like to easy convert that to a map, the key being the age, and the value a list of the names. Pretty sure there is a Kotlin way to do that, but I'm a bit puzzled about the examples I can find about associate, associateBy and all this kind of stuff!

Thanks for your help!

VR

Upvotes: 2

Views: 1929

Answers (1)

sidgate
sidgate

Reputation: 15244

Kotlin has groupBy function, which take two parameters, keyselector and value selector lambdas

val someoneList = listOf<Someone>(Someone("Joe", 12), Someone("Bill", 15), Someone("Nancy", 12))
val grouped = someoneList.groupBy ({ it.age }, {it.name})

Upvotes: 7

Related Questions