← All languages
Kotlin function of the day
Random

windowed

Return a list of snapshots of a sliding window over the collection.

Description

The windowed function returns a list of element ranges of the given size as it slides along the collection one element at a time. You can configure the step size and whether to include partial windows at the end.

By default, step is 1 and partialWindows is false, meaning only full-size windows are returned. An optional transform function can be applied to each window.

windowed is useful for computing moving averages, detecting patterns, or processing overlapping subsequences.

Arguments

NameDescriptionOptional
size The size of each window. No
step The number of elements to move the window by. Defaults to 1. Yes
partialWindows Whether to include partial windows at the end. Defaults to false. Yes
transform A lambda applied to each window. Yes

Example

val numbers = listOf(1, 2, 3, 4, 5)
val windows = numbers.windowed(3)
println(windows)  // [[1, 2, 3], [2, 3, 4], [3, 4, 5]]

Reference