Kotlin Convert List to Map

October 21, 2018

Convert object list to map by specifying the key.

val itemsMap = items.associateBy {
    it.id
}

Convert object list to map by specifiying key and value.

val itemsMap = items.associateBy({it.id}, {it.name})

Convert object list to MutableMap.

val itemsMap = items.associateByTo(mutableMapOf()) {
    it.id
}
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.