create a map from list kotlin
To create a map from a list in Kotlin, you can follow these steps:
- Create a list of key-value pairs using the
listOf()
function. Each pair should consist of a key and a corresponding value. For example:
val keyValueList = listOf(
"key1" to "value1",
"key2" to "value2",
"key3" to "value3"
)
- Convert the list of key-value pairs to a map using the
toMap()
function. This function takes the list as its argument and returns a map where the keys are the keys from the list, and the values are the corresponding values. For example:
val map = keyValueList.toMap()
- Optionally, you can also specify a custom order for the keys in the resulting map by using a
LinkedHashMap
. This ensures that the order of the keys is preserved. To do this, you can replace the previous step with the following:
val map = linkedMapOf(*keyValueList.toTypedArray())
That's it! You have successfully created a map from a list in Kotlin.