How to iterate over hashmap in Kotlin?

后端 未结 3 2126
礼貌的吻别
礼貌的吻别 2020-12-08 12:51

How to iterate over HashMap in Kotlin?

typealias HashMap = HashMap (source)
相关标签:
3条回答
  • For the above answer, be careful with Android below N!

    map.forEach { key, value -> println("$key = $value") }
    

    reference to Java 8 api which leads to:

    Rejecting re-init on previously-failed class java.lang.Class<T>
    

    map.forEach { (key, value) -> println("$key = $value") }
    

    is Kotlin feature

    0 讨论(0)
  • 2020-12-08 13:26

    It's not that difficult:

    for ((key, value) in map) {
        println("$key = $value")
    }
    

    OR
    (Updated in accordance with @RuckusT-Boom's and @KenZira's information.)

     map.forEach { (key, value) -> println("$key = $value") }
    
    0 讨论(0)
  • 2020-12-08 13:30

    Another way that has not been mentioned is:

    val mapOfItems = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
    mapOfItems.map { (key, value) -> println("$key = $value") }
    
    0 讨论(0)
提交回复
热议问题