val colors: List<Color> = listOf(
Color("SILVER", "#C0C0C0"),
Color("GOLD", "#FFD700"),
Color("OLIVE", "#808000")
)
1. associate() function
// Add mapping from name to hex of Color object
val map: Map<String, String> = colors.associate { Pair(it.name, it.hex) }
// or use
// val map: Map<String, String> = colors.associate { it.name to it.hex }
2. associateBy() function
val map: Map<String, String> = colors.associateBy({it.name}, {it.hex})
3. map() function
val map: Map<String, String> = colors.map { it.name to it.hex }.toMap()
4. Custom Routine
val map: MutableMap<String, String> = HashMap()
for (color in colors) {
map[color.name] = color.hex
}
Kotlin list 转 map
最新推荐文章于 2024-06-25 23:16:46 发布