Kotlin Array.unzip()

Kotlin Array.unzip() Tutorial

The Array.unzip() function in Kotlin is used to transform an array of pairs into a pair of lists, effectively separating the elements of the pairs into two separate lists.

This function is beneficial when working with data organized as pairs and you need to separate the elements into distinct lists for further processing.

This tutorial will explore the syntax of the Array.unzip() function and provide examples of its usage in Kotlin arrays.

Syntax

The syntax of the Array.unzip() function is as follows:

fun <T, U> Array<Pair<T, U>>.unzip(): Pair<List<T>, List<U>>

Example for Array.unzip() function

In this example, we’ll use unzip() to separate the elements of pairs in an array into two lists.

Kotlin Program

fun main() {
    val pairsArray = arrayOf(Pair("apple", 5), Pair("banana", 3), Pair("orange", 7))

    // Using unzip() to separate the elements of pairs into two lists
    val (fruits, quantities) = pairsArray.unzip()

    // Printing the original array and the resulting lists
    println("Pairs Array:\n${pairsArray.contentToString()}\n")
    println("Fruits:\n$fruits\n")
    println("Quantities:\n$quantities")
}

Output

Pairs Array:
[(apple, 5), (banana, 3), (orange, 7)]

Fruits:
[apple, banana, orange]

Quantities:
[5, 3, 7]

Summary

In this tutorial, we’ve covered the Array.unzip() function in Kotlin arrays, its syntax, and how to use it to transform a list of pairs into a pair of lists.