Skip to main content

How to convert a HashMap to an Array or a List in Kotlin

How to convert a HashMap to an Array or a List in Kotlin.

Here's a step-by-step tutorial on how to convert a HashMap to an Array or a List in Kotlin.

Converting a HashMap to an Array

To convert a HashMap to an Array in Kotlin, you can follow these steps:

Step 1: Create a HashMap

val hashMap = HashMap<Int, String>()
hashMap[1] = "Apple"
hashMap[2] = "Banana"
hashMap[3] = "Orange"

Step 2: Convert the HashMap to an Array

val array = hashMap.values.toTypedArray()

In this step, we use the values property of the HashMap to get a Collection of all the values in the HashMap. Then we use the toTypedArray() function to convert the Collection to an Array.

Step 3: Access the Array elements

for (item in array) {
println(item)
}

You can now access the elements in the Array using a loop or any other array operation.

Converting a HashMap to a List

To convert a HashMap to a List in Kotlin, you can follow these steps:

Step 1: Create a HashMap

val hashMap = HashMap<Int, String>()
hashMap[1] = "Apple"
hashMap[2] = "Banana"
hashMap[3] = "Orange"

Step 2: Convert the HashMap to a List

val list = hashMap.values.toList()

In this step, we use the values property of the HashMap to get a Collection of all the values in the HashMap. Then we use the toList() function to convert the Collection to a List.

Step 3: Access the List elements

for (item in list) {
println(item)
}

You can now access the elements in the List using a loop or any other list operation.

That's it! You have now learned how to convert a HashMap to an Array or a List in Kotlin.