Kotlin List unzip()
Syntax & Examples


Syntax of List.unzip()

The syntax of List.unzip() extension function is:

fun <T, R> Iterable<Pair<T, R>>.unzip(): Pair<List<T>, List<R>>

This unzip() extension function of List returns a pair of lists, where first list is built from the first values of each pair from this collection, second list is built from the second values of each pair from this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list containing pairs of an integer and a character.
  • We apply the unzip() function to split the pairs into two lists: firstList containing the first values of each pair and secondList containing the second values.
  • Finally, we print both lists to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(Pair(1, 'a'), Pair(2, 'b'), Pair(3, 'c'));
    val (firstList, secondList) = list.unzip();
    println("First List: \${firstList.joinToString()}\nSecond List: \${secondList.joinToString()}");
}

Output

First List: 1, 2, 3
Second List: a, b, c

2 Example

In this example,

  • We create a list named list containing pairs of a character and an integer.
  • We apply the unzip() function to split the pairs into two lists: firstList containing the first values of each pair and secondList containing the second values.
  • Finally, we print both lists to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(Pair('a', 1), Pair('b', 2), Pair('c', 3));
    val (firstList, secondList) = list.unzip();
    println("First List: \${firstList.joinToString()}\nSecond List: \${secondList.joinToString()}");
}

Output

First List: a, b, c
Second List: 1, 2, 3

3 Example

In this example,

  • We create a list named list containing pairs of a string and an integer.
  • We apply the unzip() function to split the pairs into two lists: firstList containing the first values of each pair and secondList containing the second values.
  • Finally, we print both lists to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(Pair("apple", 1), Pair("banana", 2), Pair("cherry", 3));
    val (firstList, secondList) = list.unzip();
    println("First List: \${firstList.joinToString()}\nSecond List: \${secondList.joinToString()}");
}

Output

First List: apple, banana, cherry
Second List: 1, 2, 3

Summary

In this Kotlin tutorial, we learned about unzip() extension function of List: the syntax and few working examples with output and detailed explanation for each example.