How to iterate over hashmap in Kotlin?

How to iterate over hashmap in Kotlin?

Its not that difficult:

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

OR
(Updated in accordance with @RuckusT-Booms and @KenZiras information.)

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

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

How to iterate over hashmap in 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) }

Leave a Reply

Your email address will not be published.