如何在Kotlin中迭代hashmap?

时间:2017-11-09 14:18:35

标签: kotlin kotlin-extension

如何在Kotlin中迭代HashMap

typealias HashMap<K, V> = HashMap<K, V> (source)

4 个答案:

答案 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")
    }

}