The zip() extension function in Kotlin returns a list of pairs built from the elements of this set and the other collection or array with the same index. It can also return a list of values built from the elements of this set and the other collection or array using a provided transform function.
There are 4 variations for the syntax of Set.zip() extension function. They are:
infix fun <T, R> Set<T>.zip(other: Array<out R>): List<Pair<T, R>>
This extension function returns a list of pairs built from the elements of this set and the other array with the same index. The returned list has the length of the shortest collection.
Returns value of type List<Pair<T, R>>
.
fun <T, R, V> Set<T>.zip(other: Array<out R>, transform: (a: T, b: R) -> V): List<V>
This extension function returns a list of values built from the elements of this set and the other array with the same index using the provided transform function applied to each pair of elements. The returned list has the length of the shortest collection.
Returns value of type List<V>
.
infix fun <T, R> Set<T>.zip(other: Iterable<R>): List<Pair<T, R>>
This extension function returns a list of pairs built from the elements of this set and the other collection with the same index. The returned list has the length of the shortest collection.
Returns value of type List<Pair<T, R>>
.
fun <T, R, V> Set<T>.zip(other: Iterable<R>, transform: (a: T, b: R) -> V): List<V>
This extension function returns a list of values built from the elements of this set and the other collection with the same index using the provided transform function applied to each pair of elements. The returned list has the length of the shortest collection.
Returns value of type List<V>
.
Using zip() to create a list of pairs from a set and an array.
For example,
fun main() {
val numbers = setOf(1, 2, 3)
val words = arrayOf("one", "two", "three")
val result = numbers zip words
println(result)
}
[(1, one), (2, two), (3, three)]
Using zip() to create a list of strings from a set and a list, applying a transform function.
For example,
fun main() {
val numbers = setOf(1, 2, 3)
val words = listOf("one", "two", "three")
val result = numbers.zip(words) { a, b -> "$a -> $b" }
println(result)
}
[1 -> one, 2 -> two, 3 -> three]
Using zip() to create a list of pairs from two sets.
For example,
fun main() {
val set1 = setOf(1, 2, 3)
val set2 = setOf(4, 5, 6)
val result = set1 zip set2
println(result)
}
[(1, 4), (2, 5), (3, 6)]
In this Kotlin tutorial, we learned about zip() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.