如何在Kotlin
中迭代HashMap?
typealias HashMap<K, V> = HashMap<K, V> (source)
答案 0 :(得分:109)
这并不困难:
for ((key, value) in map) {
println("$key = $value")
}
或强>
(已更新,符合@RuckusT-Boom's和@KenZira's信息。)
map.forEach { (key, value) -> println("$key = $value") }
答案 1 :(得分:37)
Android
以下N
!map.forEach { key, value -> println("$key = $value") }
引用Java 8
api导致:
Rejecting re-init on previously-failed class java.lang.Class<T>
map.forEach { (key, value) -> println("$key = $value") }
是Kotlin
功能
答案 2 :(得分:2)
未提及的另一种方法是:
val mapOfItems = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
mapOfItems.map { (key, value) -> println("$key = $value") }
答案 3 :(得分:2)
使用“for循环”或“forEach”或“迭代器”For your Reference
fun main(args : Array<String>) {
val items = HashMap<String, String>()
items["1"] = "USA"
items["2"] = "Japan"
items["3"] = "India"
//for loop example
println("\n-- Example 1.1 -- ");
for ((k, v) in items) {
println("$k = $v")
}
// forEach example
println("\n-- Example 1.2 --");
items.forEach { (k, v) ->
println("$k = $v")
}
//Iterator example
println("\n-- Example 1.3 --");
val itr = items.keys.iterator()
while (itr.hasNext()) {
val key = itr.next()
val value = items[key]
println("${key}=$value")
}
}