从地图中,我们可以使用map轻松进入列表
mapNumber.map{ it.key }
Run Code Online (Sandbox Code Playgroud)
但是,如果我想要两个列表,并且想要避免做map两次
val numbersInt = mapNumbers.map{ it.key }
val numbersStr = mapNumbers.map{ it.value }
Run Code Online (Sandbox Code Playgroud)
所以我可以在下面写一些东西
fun main(args: Array<String>) {
val mapNumbers = mapOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))
val numbersInt = mutableListOf<Int>()
val numbersStr = mutableListOf<String>()
for ((key, value) in mapNumbers) {
numbersInt.add(key)
numbersStr.add(value)
}
print(numbersInt)
print(numbersStr)
}
Run Code Online (Sandbox Code Playgroud)
但这并不好,因为我必须使用mutableListOf. 我想知道是否有任何收集功能可以帮助我们实现这一目标?
我建议使用unzip()标准库函数。
fun main(args: Array<String>) {
val mapNumbers = mapOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))
val (numbersInt, numbersStr) = mapNumbers.toList().unzip()
print(numbersInt)
print(numbersStr)
}
Run Code Online (Sandbox Code Playgroud)
在这里,我已将 转换map为Pair对象列表。然后调用unzip()方法。使用Destructuring Declaration,我已将从 返回的值分配unzip()给这些变量。请参阅:https : //kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/unzip.html。希望你会喜欢这个解决方案。
| 归档时间: |
|
| 查看次数: |
2792 次 |
| 最近记录: |