【问题标题】:How to iterate over hashmap in Kotlin?如何在 Kotlin 中迭代 hashmap?
【发布时间】:2022-05-03 19:19:18
【问题描述】:

如何在Kotlin 中迭代HashMap

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

【问题讨论】:

    标签: kotlin kotlin-extension


    【解决方案1】:

    没那么难:

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


    更新符合@RuckusT-Boom's@KenZira's信息。)

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

    【讨论】:

    • 值得注意的是,第二个版本可能会导致 Android 出现问题,因此您可能需要使用map.forEach { (key, value) -&gt; println("$key = $value") }
    • @RuckusT-Boom 以什么方式引起问题?
    • Android 没有(或在发表评论时没有)完全支持 Java 8,第二个示例是 Java 8 调用。使用 Kotlin 解构的等效调用看起来非常相似,但您需要将参数 { (key, value) -&gt; ... } 括起来。 Ken Zira 在他的回答中提供了更多信息。
    • 我们发现 @RuckusT-Boom 的方式在 Android 上更好 :) (由于 ClassNotFoundException 我们很难弄清楚)
    • @RuckusT-Boom 的回答是正确的,我们在不同 API 级别的发布测试中遇到了这个问题,并且不太清楚它为什么会崩溃,错误消息也具有误导性
    【解决方案2】:

    对于上面的答案,注意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 特征

    【讨论】:

    • 是的,我也为此浪费了半天时间。 for ((key, val) ...) 解决了这个问题。
    【解决方案3】:

    另一种没有提到的方式是:

    val mapOfItems = hashMapOf(1 to "x", 2 to "y", -1 to "zz")
    mapOfItems.map { (key, value) -> println("$key = $value") }
    

    【讨论】:

    • 值得注意的是,这对于地图功能来说是相当反模式的。它用于将一种类型的迭代映射到另一种类型的迭代。不是为了简单地迭代。为此,我们有 forEach
    【解决方案4】:

    使用“for循环”或“forEach”或“迭代器”

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

    【讨论】:

      【解决方案5】:

      在 Kotlin 中使用 HashMap 检索消息。

      fun main() {
      
          // Adding messages to arrayList
          val myMsg = arrayListOf(
              Message(1, "A", "10-02-2022"),
              Message(2, "B", "10-02-2022"),
              Message(3, "C", "11-02-2022"),
              Message(4, "D", "11-02-2022"),
              Message(5, "E", "11-02-2022"),
              Message(6, "F", "12-02-2022"),
              Message(7, "G", "12-02-2022"),
              Message(8, "H", "12-02-2022"),
              Message(9, "I", "14-02-2022"),
              Message(10, "J", "14-02-2022")
          )
      
          // Getting date wise messages
          val dateWiseMessageList = myMsg.groupBy { it.date }.values
          println("Total sections are ${dateWiseMessageList.size}")
      
          val myMessageMap = HashMap<Int, List<Message>>()
      
          // Storing date wise messages to HashMap with Key and Value as multiple messages
          for ((index, value) in dateWiseMessageList.withIndex()) {
              println("the element at $index is $value")
              myMessageMap[index] = value
          }
      
          // Retrieve messages in date wise section
          for ((key, value) in myMessageMap) {
              println("Section $key data are")
              for (i in value.indices) {
                  println(" Id = ${value[i].id} Message = ${value[i].msg} Date = ${value[i].date}")
              }
          }
      }
      

      消息数据类

      data class Message(val id: Int, val msg: String, val date: String)
      

      output

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多