180

How to iterate over HashMap in Kotlin?

typealias HashMap<K, V> = HashMap<K, V> (source)
Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
Nomi
  • 1,981
  • 2
  • 8
  • 10

5 Answers5

377

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") }
jungledev
  • 4,195
  • 1
  • 37
  • 52
Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
  • 49
    It's worth noting the second version can cause issues on Android, so you may want to use `map.forEach { (key, value) -> println("$key = $value") }` – Ruckus T-Boom Nov 09 '17 at 17:04
  • 1
    @RuckusT-Boom in what way does it cause issues? – Anigif May 01 '18 at 11:12
  • 13
    Android doesn't (or didn't at the time of that comment) have full support for Java 8, and the second example is a Java 8 call. The equivalent call using Kotlin destructuring looks very similar, but you need brackets around the arguments `{ (key, value) -> ... }`. Ken Zira has more info in his answer. – Ruckus T-Boom May 03 '18 at 03:31
  • 1
    We found out the hard way that @RuckusT-Boom's way is better on Android :) (Due to a ClassNotFoundException we hard a hard time figuring out) – Micha May 24 '18 at 15:32
  • 2
    @RuckusT-Boom's answer is the correct one, we had this issue during release tests on different API Levels, and it was not very clear why it was crashing, the error message is also misleading – Alaa Eddine Cherbib Jun 10 '18 at 07:08
  • Surprisingly and frustratingly, if brackets were left out on android, it is a runtime error! – rpattabi Aug 23 '18 at 13:09
84

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

Alex Romanov
  • 11,453
  • 6
  • 48
  • 51
Ken Zira
  • 1,170
  • 2
  • 10
  • 12
10

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") }
Whitecat
  • 3,882
  • 7
  • 48
  • 78
  • 1
    It's worth noting that this is quite anti-pattern for the map-function. It is meant for mapping an iterable of one type into an iterable of another type. Not for simply iterating. We have `forEach` for that. – Sebastian Oct 26 '21 at 11:54
8

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

}
Sibin Rasiya
  • 1,132
  • 1
  • 11
  • 15
1

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

Nk P
  • 41
  • 4