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:

1.
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>>.

2.
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,

  1. Create a set of integers.
  2. Use zipWithNext() to create pairs of adjacent elements.
  3. 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,

  1. Create a set of strings.
  2. Use zipWithNext() with a transform function to concatenate adjacent elements.
  3. 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,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use zipWithNext() to create pairs of adjacent elements.
  4. 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.