DEV Community

loading...

Kotlin Collections - zipWithNext

λeo
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()
//[(1,2),(2,3),(3,4),(4,5)]

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

Discussion (0)