Search code examples
listdictionarykotlincollectors

Merge List<Keys> and List<Values> into List<Hashmap<Key,Value>>


i have two list;

val keys: List<String> = listOf("key1", "key2", "key3"...)
val values: List<String> = listOf("value1", "value2", "value3"...)

How can i merge them into one List<Hashmap<Key,Value>>? like;

println(List<Hashmap<Key,Value>>): [[key1 = value1], [key2 = value2], [key3 = value3]...


Solution

  • In idiomatic Kotlin, that would look like this:

    val keys: List<String> = listOf("key1", "key2", "key3")
    val values: List<String> = listOf("value1", "value2", "value3")
    
    val result = keys.zip(values).map { hashMapOf(it) }
    

    (runnable demo)

    Here, hashMapOf(...) accepts pairs (Pair<K, V>), and that's exactly the elements that zip produces.

    Alternatively, you can use the overload of zip that accepts a lambda and maps the pairs without an additional call to map:

    val result = keys.zip(values) { k, v -> hashMapOf(k to v) }
    

    (runnable demo)

    The result is a list of maps, each containing a single key mapped to the value.


    An opposite option is to create a single map containing all of the pairs, which can be produced as follows:

    val result = HashMap(keys.zip(values).toMap())
    

    (runnable demo)