I'm trying to create a map that takes two values from a list and uses the first value as the key and the second key as the value but I can't figure out how to do it.
Let's say I have a list like the following.
-e
, normal
, -t
, flat
, -s
, test
How can I create a map from that list that looks like the following?
-e
to normal
, -t
to flat
, -s
to test
The standard way to convert a list to a map is with the associate() function. It returns a map containing key-value pairs provided by the transform function applied to the given list elements.
You can use the map() function to easily convert a list of one type to a list of another type. It returns a list containing the results of applying the specified transform function to each element in the original list. That's all about conversion between lists of different types in Kotlin.
Add and update entries To add a new key-value pair to a mutable map, use put() . When a new entry is put into a LinkedHashMap (the default map implementation), it is added so that it comes last when iterating the map. In sorted maps, the positions of new elements are defined by the order of their keys.
If you want to use built in functions, chunked
can be a quick way to do this:
val arguments = listOf("-e", "normal", "-t", "flat", "-s", "test")
val map: Map<String, String> = arguments
.chunked(2) { (switch, value) -> switch to value }
.toMap()
println(map) // {-e=normal, -t=flat, -s=test}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With