I want to group by id.
[
{
"id": 1,
"name": "a"
},
{
"id": 2,
"name": "b"
},
{
"id": 3,
"name": "c"
}
]
The results should be as follows:
{
"1": "a",
"2": "b",
"3": "c"
}
What is the most idiomatic way of doing this in Kotlin?
CodePudding user response:
Your question only shows JSON, so I'm not sure if this is about JSON serialization or Kotlin. Since it's tagged kotlin
, I'm assuming you're already deserializing the initial list to Kotlin with something like this
data class NamedThing(val id: Int, val name: String)
val list: List<NamedThing> = TODO("somehow you're getting a list of those here")
If you already have this, you can easily create a map from this list using:
val map = list.associate { it.id to it.name }