windowed
- Kotlin course
- Advanced
- Lesson 55/83
- 5 min
Learn windowing with windowed.
windowed
windowed splits a collection into sliding windows. Each window has a given size; an optional step controls the shift.
Example: listOf(1, 2, 3, 4).windowed(2) returns [[1, 2], [2, 3], [3, 4]]. windowed(2, step = 2) gives [[1, 2], [3, 4]]; windows do not overlap. This pattern is useful for moving averages and time-series analysis.
step and partialWindows
The step parameter sets the window shift. With partialWindows = true, the trailing partial window is included.
Example: listOf(1, 2, 3, 4, 5).windowed(3, step = 2) returns [[1, 2, 3], [3, 4, 5]]. With partialWindows = true, listOf(1, 2, 3, 4, 5).windowed(3, step = 2, partialWindows = true) appends [5]. These parameters fine-tune window behavior.
Practice Compute a moving average
In main assign the result of listOf(1, 2, 3, 4, 5).windowed(3) { it.average() } to a variable and print it with println.
Starter code
// in main split the list 1..5 with windowed(3)
// take each window's average and printSample solution
fun main() {
val avg = listOf(1, 2, 3, 4, 5).windowed(3) { it.average() }
println(avg)
}Expected output
[2.0, 3.0, 4.0]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does listOf(1, 2, 3, 4).windowed(2) return?
- [[1, 2], [3, 4]]
- [[1, 2], [2, 3], [3, 4]] Correct answer
- [[1, 2, 3, 4]]
- [1, 2, 3, 4]
Explanation: windowed(2) uses default step 1 to slide.
2 Complete the windowed call
val windows = listOf(1, 2, 3, 4).____(2)
val windows = listOf(1, 2, 3, 4).windowed(2)
Explanation: windowed(2) yields sliding windows of size 2.
3 Match the windowed parts
| Term | Meaning |
|---|---|
windowed(2) |
Window size |
step = 2 |
Shift |
partialWindows = true |
Partial window |
[[1, 2], [2, 3]] |
Result |