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?
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.
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)
}
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