Kotlin

windowed and chunked

admin by @admin ADMIN
Jun 13, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`chunked(n)` splits a list into NON-overlapping pieces of size n. `windowed(n)` slides a fixed-size window across — overlapping. Useful for moving averages, n-grams, batch APIs.
Kotlin
Raw
fun main() {
    val nums = listOf(1, 2, 3, 4, 5, 6, 7)

    // chunked — disjoint pieces
    println(nums.chunked(3))                              // [[1,2,3], [4,5,6], [7]]

    // windowed — overlapping window
    println(nums.windowed(3))                             // [[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7]]
    println(nums.windowed(3, step = 2))                   // [[1,2,3], [3,4,5], [5,6,7]]
    println(nums.windowed(3, partialWindows = true))      // includes [6,7] and [7]

    // Moving 3-pt average via windowed
    val readings = listOf(10.0, 13.0, 12.0, 18.0, 14.0, 22.0)
    val movingAvg = readings.windowed(3).map { it.average() }
    println(movingAvg)                                    // [11.67, 14.33, 14.67, 18.0]

    // chunked is perfect for batching API calls
    val ids = (1..100).toList()
    ids.chunked(25).forEach { batch ->
        // Send each batch of 25 IDs to the API
    }

    // zipWithNext — pairs of consecutive items (window of 2, step 1)
    println(readings.zipWithNext { a, b -> b - a })       // [3.0, -1.0, 6.0, -4.0, 8.0]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.