DEV Community

λeo
λeo

Posted on • Edited on

1 2

Kotlin Collections - zipWithNext

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]

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay