Reputation: 11287
In kotlin, if I have a pair I can get a list of first values and second values like this:
val(firstList, secondList) = listOfPairs.unzip()
// listOfPairs: List<Pair<String, Long>>
How can I do the same for a Triple
?
Upvotes: 0
Views: 731
Reputation: 9454
How bout something like this:
fun <X>List<Triple<X,X,X>>.unzip(): List<List<X>> {
return fold(listOf(ArrayList<X>(), ArrayList<X>(), ArrayList<X>())){ r, i ->
r[0].add(i.first)
r[1].add(i.second)
r[2].add(i.third)
r
}
}
Usage:
val triplesList = listOf(Triple(1,"s",3), Triple(1,"u",3), Triple(1,"p",3))
val (listOne, listTwo, listThree) = triplesList.unzip()
println("ListOne: $listOne")
println("ListTwo: $listTwo")
println("ListThree: $listThree")
/* Output:
ListOne: [1, 1, 1]
ListTwo: [s, u, p]
ListThree: [3, 3, 3]
*/
Upvotes: 1
Reputation: 16159
How about this?
val firstList = listOf(triple1, triple2).map {it.first }
val secondList = listOf(triple1, triple2).map { it.second }
val thirdList = listOf(triple1, triple2).map { it.third }
or
val result = listOf(triple1, triple2).map {
Triple(it.first, it.second, it.third)
}
Upvotes: 0