Kotlin Set unzip()
Syntax & Examples


Set.unzip() extension function

The unzip() extension function in Kotlin returns a pair of lists, where the first list is built from the first values of each pair in the collection, and the second list is built from the second values of each pair in the collection.


Syntax of Set.unzip()

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

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

This unzip() extension function of Set 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.

Return Type

Set.unzip() returns value of type Pair, List>.



✐ Examples

1 Unzipping a set of pairs of integers and strings

Using unzip() to separate a set of pairs of integers and strings into two lists.

For example,

  1. Create a set of pairs of integers and strings.
  2. Use unzip() to separate the pairs into two lists.
  3. Print the resulting pair of lists.

Kotlin Program

fun main() {
    val pairs = setOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))
    val (ints, strings) = pairs.unzip()
    println(ints)
    println(strings)
}

Output

[1, 2, 3]
[one, two, three]

2 Unzipping a set of pairs of strings and doubles

Using unzip() to separate a set of pairs of strings and doubles into two lists.

For example,

  1. Create a set of pairs of strings and doubles.
  2. Use unzip() to separate the pairs into two lists.
  3. Print the resulting pair of lists.

Kotlin Program

fun main() {
    val pairs = setOf(Pair("one", 1.1), Pair("two", 2.2), Pair("three", 3.3))
    val (strings, doubles) = pairs.unzip()
    println(strings)
    println(doubles)
}

Output

[one, two, three]
[1.1, 2.2, 3.3]

3 Unzipping a set of pairs of custom objects and integers

Using unzip() to separate a set of pairs of custom objects and integers into two lists.

For example,

  1. Create a data class.
  2. Create a set of pairs of custom objects and integers.
  3. Use unzip() to separate the pairs into two lists.
  4. Print the resulting pair of lists.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val pairs = setOf(Pair(Person("Alice", 30), 1), Pair(Person("Bob", 25), 2), Pair(Person("Charlie", 35), 3))
    val (people, ints) = pairs.unzip()
    println(people)
    println(ints)
}

Output

[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)]
[1, 2, 3]

Summary

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