Kotlin List zipWithNext()
Syntax & Examples


Syntax of List.zipWithNext()

There are 2 variations for the syntax of List.zipWithNext() extension function. They are:

1.
fun <T> Iterable<T>.zipWithNext(): List<Pair<T, T>>

This extension function returns a list of pairs of each two adjacent elements in this collection.

2.
fun <T, R> Iterable<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 an each pair of two adjacent elements in this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list containing the characters 'a', 'p', 'p', 'l', 'e'.
  • We use the zipWithNext() extension function on list to create a list of pairs of each two adjacent elements.
  • We iterate over the pairs using a loop and print each pair to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;a&quot;, &quot;p&quot;, &quot;p&quot;, &quot;l&quot;, &quot;e&quot;)
    val pairs = list.zipWithNext()
    for ((first, second) in pairs) {
        println(&quot;Pair: (\$first, \$second)&quot;)
    }
}

Output

Pair: (a, p)
Pair: (p, p)
Pair: (p, l)
Pair: (l, e)

2 Example

In this example,

  • We create a list named list containing the integers 10, 20, 30.
  • We use the zipWithNext() extension function on list with a transform function that calculates the sum of adjacent elements.
  • We iterate over the pairs using a loop and print the sum of adjacent elements to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(10, 20, 30)
    val pairs = list.zipWithNext { a, b -> a + b }
    for (pair in pairs) {
        println(&quot;Sum of adjacent elements: \$pair&quot;)
    }
}

Output

Sum of adjacent elements: 30
Sum of adjacent elements: 50

3 Example

In this example,

  • We create a list named list containing the strings 'apple', 'banana', 'cherry'.
  • We use the zipWithNext() extension function on list with a transform function that calculates the sum of lengths of adjacent strings.
  • We iterate over the pairs using a loop and print the sum of lengths of adjacent strings to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;)
    val pairs = list.zipWithNext { a, b -> a.length + b.length }
    for (pair in pairs) {
        println(&quot;Sum of lengths of adjacent strings: \$pair&quot;)
    }
}

Output

Sum of lengths of adjacent strings: 11
Sum of lengths of adjacent strings: 12

Summary

In this Kotlin tutorial, we learned about zipWithNext() extension function of List: the syntax and few working examples with output and detailed explanation for each example.