2017-07-24 82 views
2

我想传统的地图转换:转换映射到地图列表中科特林

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

到地图列表与固定键像这样:

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

现在我有一个该解决方案看起来不太好,并没有真正利用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 
} 

回答

3

只需使用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) 
    } 
}