Given each list item, we compute both key & value for its corresponding map entry.
listItem → **key**, **value**
list.associate { item -> /* return Pair */ }
Example (Simple)
Example (Simple)
Given a List<String>
where each list item is of the format key | value
, create a Map<String, Int>
fun main() {
val list = listOf(
"A | 1", "B | 2", "C | 3"
)
val map = list.associate {
val (key, value) = it.split(" | ")
key to value.toInt()
}
println(map)
}
// Output : {A=1, B=2, C=3}
Example 2 (OOPs)
Example 2 (OOPs)
Given a List<Person(id, name)>
, create a Map<String, String>
where key is person’s id and value is person’s name.
data class Person(
val id: String,
val name: String
)
fun main() {
val persons = listOf(
Person("A1", "Alpha"),
Person("B1", "Beta")
)
val idToNameMap = persons.associate {
it.id to it.name
}
println(idToNameMap)
}
// Output : {A1=Alpha, B1=Beta}