How to iterate over hashmap in Kotlin?

KotlinKotlin Extension

Kotlin Problem Overview


How to iterate over HashMap in Kotlin?

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

Kotlin Solutions


Solution 1 - Kotlin

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

Solution 2 - Kotlin

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

Solution 3 - Kotlin

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

Solution 4 - Kotlin

Use 'for loop' or 'forEach' or 'Iterator'

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

}

Solution 5 - Kotlin

Retrieve messages using HashMap in Kotlin.

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

Message data class

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

output

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNomiView Question on Stackoverflow
Solution 1 - KotlinAlexander RomanovView Answer on Stackoverflow
Solution 2 - KotlinKen ZiraView Answer on Stackoverflow
Solution 3 - KotlinWhitecatView Answer on Stackoverflow
Solution 4 - KotlinSibin RasiyaView Answer on Stackoverflow
Solution 5 - KotlinNk PView Answer on Stackoverflow