简体   繁体   English

将地图转换为Kotlin中的地图列表

[英]Convert maps to list of maps in Kotlin

I am trying to convert a traditional map: 我正在尝试转换传统地图:

1 -> "YES",
2 -> "NO",
3 -> "YES",
...

To a list of maps with fixed keys like such: 到具有固定键的地图列表,如下所示:

[
  <number -> 1,
   answer -> "YES">,
  <number -> 2,
   answer -> "NO">,
  ...
]

Right now I have a solution which does not look good and is not really making use of Kotlin's functional features. 现在我有一个看起来不太好的解决方案,并没有真正利用Kotlin的功能特性。 I was wondering if there was a clearer solution that did: 我想知道是否有更清晰的解决方案:

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
}

Just to use Map#map is sufficient for you, for example: 只需使用Map#map就足够了,例如:

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) 
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM