List 将地图转换为Kotlin中的地图列表
我正在尝试转换传统地图:List 将地图转换为Kotlin中的地图列表,list,dictionary,kotlin,List,Dictionary,Kotlin,我正在尝试转换传统地图: 1 -> "YES", 2 -> "NO", 3 -> "YES", ... 要查看具有固定键的地图列表,请执行以下操作: [ <number -> 1, answer -> "YES">, <number -> 2, answer -> "NO">, ... ] [ 1. 回答->“是”>, 2. 回答->“不”>, ... ] 现在我有一个看起来不太好的解决方案,它并没有
1 -> "YES",
2 -> "NO",
3 -> "YES",
...
要查看具有固定键的地图列表,请执行以下操作:
[
<number -> 1,
answer -> "YES">,
<number -> 2,
answer -> "NO">,
...
]
[
1.
回答->“是”>,
2.
回答->“不”>,
...
]
现在我有一个看起来不太好的解决方案,它并没有真正利用Kotlin的功能特性。我想知道是否有更清晰的解决方案:
fun toListOfMaps(map: Map<Int, String>): List<Map<String, Any>> {
val listOfMaps = emptyList<Map<String, Any>>().toMutableList()
for (entry in map) {
val mapElement = mapOf(
"number" to entry.component1(),
"answer" to entry.component2()
)
listOfMaps.add(mapElement)
}
return listOfMaps
}
趣味toListOfMaps(地图:地图):列表{
val listofmap=emptyList().toMutableList()
用于(地图中的条目){
val mapElement=mapOf(
条目.component1()的“编号”,
条目的“答案”。组件2()
)
添加(mapElement)
}
返回地图列表
}
仅使用就足够了,例如:
fun toListOfMaps(map: Map<Int, String>): List<Map<String, Any>> {
// v--- destructuring `Map.Entry` here
return map.map { (number, answer) ->
mapOf("number" to number, "answer" to answer)
}
}
趣味toListOfMaps(地图:地图):列表{
//v---解构`映射.条目`此处
return map.map{(数字,答案)->
mapOf(“数字”到数字,“答案”到答案)
}
}