Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: How to map into two lists

Tags:

kotlin

From a map, we could use map to break into list easily using

mapNumber.map{ it.key }

However, if I want both list, and want to avoid doing the map twice

val numbersInt = mapNumbers.map{ it.key }
val numbersStr = mapNumbers.map{ it.value }

So I could write something below

fun main(args: Array<String>) {
    val mapNumbers = mapOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))

    val numbersInt = mutableListOf<Int>()
    val numbersStr = mutableListOf<String>()

    for ((key, value) in mapNumbers) {
        numbersInt.add(key)
        numbersStr.add(value)
    }

    print(numbersInt)
    print(numbersStr)   
}

But that's not nice, as I have to use mutableListOf. I wonder if there's any collection function that could help us achieve that?

like image 445
Elye Avatar asked Dec 17 '22 17:12

Elye


2 Answers

I'd suggest to use unzip() standard library function.

fun main(args: Array<String>) {
    val mapNumbers = mapOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))

    val (numbersInt, numbersStr) = mapNumbers.toList().unzip()

    print(numbersInt)
    print(numbersStr)
}

Here I've converted the map into a list of Pair objects. And then called the unzip() method. Using Destructuring Declaration, I've assigned the values returned from the unzip() to these variables. See: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/unzip.html. Hope you'll like this solution.

like image 177
Abhay Agarwal Avatar answered Jan 31 '23 13:01

Abhay Agarwal


I am not sure why you discounted dyukha's comment, you can save the returned collections in any named variable you like. Sure it's two lines of code, but I would think it's still very efficient and expresses exactly what you want.

   fun main(args: Array<String>) {
        val mapNumbers = mapOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))

        val numbersInt = mapNumbers.keys
        val numbersStr = mapNumbers.values

        print(numbersInt)
        print(numbersStr)   
    }
like image 43
nPn Avatar answered Jan 31 '23 13:01

nPn