Kotlin Program to Convert Map (HashMap) to List

Example: Convert Map to List

import java.util.ArrayList
import java.util.HashMap

fun main(args: Array<String>) {

    val map = HashMap<Int, String>()
    map.put(1, "a")
    map.put(2, "b")
    map.put(3, "c")
    map.put(4, "d")
    map.put(5, "e")

    val keyList = ArrayList(map.keys)
    val valueList = ArrayList(map.values)

    println("Key List: $keyList")
    println("Value List: $valueList")

}

When you run the program, the output will be:

Key List: [1, 2, 3, 4, 5]
Value List: [a, b, c, d, e]

In the above program, we've a map of Integer and String named map. Since map contains a key, value pair, we need two lists to store each of them, namely keyList for keys and valueList for values.

We used map's keySet() method to get all the keys and created an ArrayList keyList from them. Likewise, we used map's values() method to get all the values and created an ArrayList valueList from them.

Here's the equivalent Java code: Java Program to convert map to a list.

Did you find this article helpful?