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.
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.
Set.unzip() returns value of type Pair
, List
.
Using unzip() to separate a set of pairs of integers and strings into two lists.
For example,
fun main() {
val pairs = setOf(Pair(1, "one"), Pair(2, "two"), Pair(3, "three"))
val (ints, strings) = pairs.unzip()
println(ints)
println(strings)
}
[1, 2, 3] [one, two, three]
Using unzip() to separate a set of pairs of strings and doubles into two lists.
For example,
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)
}
[one, two, three] [1.1, 2.2, 3.3]
Using unzip() to separate a set of pairs of custom objects and integers into two lists.
For example,
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)
}
[Person(name=Alice, age=30), Person(name=Bob, age=25), Person(name=Charlie, age=35)] [1, 2, 3]
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.