Kotlin Set zipWithNext()
Syntax & Examples
Set.zipWithNext() extension function
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.
Syntax of Set.zipWithNext()
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>
.
✐ Examples
1 Zipping adjacent elements in a set of integers
Using zipWithNext() to create a list of pairs of adjacent elements in a set of integers.
For example,
- Create a set of integers.
- Use zipWithNext() to create pairs of adjacent elements.
- Print the resulting list of pairs.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4)
val result = numbers.zipWithNext()
println(result)
}
Output
[(1, 2), (2, 3), (3, 4)]
2 Transforming adjacent elements in a set of strings
Using zipWithNext() with a transform function to concatenate adjacent elements in a set of strings.
For example,
- Create a set of strings.
- Use zipWithNext() with a transform function to concatenate adjacent elements.
- Print the resulting list of concatenated strings.
Kotlin Program
fun main() {
val strings = setOf("a", "b", "c", "d")
val result = strings.zipWithNext { a, b -> "$a$b" }
println(result)
}
Output
[ab, bc, cd]
3 Zipping adjacent custom objects in a set
Using zipWithNext() to create a list of pairs of adjacent custom objects in a set.
For example,
- Create a data class.
- Create a set of custom objects.
- Use zipWithNext() to create pairs of adjacent elements.
- Print the resulting list of pairs.
Kotlin Program
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)
}
Output
[(Person(name=Alice, age=30), Person(name=Bob, age=25)), (Person(name=Bob, age=25), Person(name=Charlie, age=35))]
Summary
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.