mikeb
mikeb

Reputation: 11287

Unzip for Triple in Kotlin

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

Answers (2)

Quinn
Quinn

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]
 */

Try it online!

Upvotes: 1

William Hu
William Hu

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

Related Questions