The zipWithNext() extension function in Kotlin returns a list of pairs of each two adjacent elements in this set. It can also return a list containing the results of applying a given transform function to each pair of two adjacent elements in the set.
There are 2 variations for the syntax of Set.zipWithNext() extension function. They are:
fun <T> Set<T>.zipWithNext(): List<Pair<T, T>>
This extension function returns a list of pairs of each two adjacent elements in this set.
Returns value of type List<Pair<T, T>>
.
fun <T, R> Set<T>.zipWithNext(transform: (a: T, b: T) -> R): List<R>
This extension function returns a list containing the results of applying the given transform function to each pair of two adjacent elements in this set.
Returns value of type List<R>
.
Using zipWithNext() to create a list of pairs of adjacent elements in a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4)
val result = numbers.zipWithNext()
println(result)
}
[(1, 2), (2, 3), (3, 4)]
Using zipWithNext() with a transform function to concatenate adjacent elements in a set of strings.
For example,
fun main() {
val strings = setOf("a", "b", "c", "d")
val result = strings.zipWithNext { a, b -> "$a$b" }
println(result)
}
[ab, bc, cd]
Using zipWithNext() to create a list of pairs of adjacent custom objects in a set.
For example,
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val result = people.zipWithNext()
println(result)
}
[(Person(name=Alice, age=30), Person(name=Bob, age=25)), (Person(name=Bob, age=25), Person(name=Charlie, age=35))]
In this Kotlin tutorial, we learned about zipWithNext() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.