Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a map with every two items in a list in Kotlin?

Tags:

kotlin

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

like image 866
TheLukeGuy Avatar asked Apr 28 '18 13:04

TheLukeGuy


People also ask

How do I map a list on Kotlin?

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.

How do I map a list to another list in Kotlin?

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.

How do I add elements to a map 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.


1 Answers

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}
like image 94
zsmb13 Avatar answered Sep 21 '22 04:09

zsmb13