DEV Community


Kotlin Collections - zipWithNext

Code Alchemist
Updated on ・1 min read

To retrieve adjacent elements from iterable type use zipWithNext function.

ZipWithNext method iterates over the iterable type and creates another iterable type to save the result.

It is going to take O(n) time and O(n) space.

Official Documentation

val numbers = listOf(1,2,3,4,5)

//Apply zipWithNext function to retrieve adjacent elements
val adjacentElements:List<Pair<Int,Int>> = numbers.zipWithNext()

//can modify the operation function to apply on each element.
val distanceBetweenNumbers:List<Int> = numbers.zipWithNext{ a, b -> b - a}

Discussion (0)