windowed
Returns a list of snapshots of the window of the given size sliding along this collection with the given step, where each snapshot is a list.
Several last lists may have fewer elements than the given size.
Both size and step must be positive and can be greater than the number of elements in this collection.
Since Kotlin
1.2Parameters
the number of elements to take in each window
the number of elements to move the window forward by on an each step, by default 1
controls whether or not to keep partial windows in the end if any, by default false
which means partial windows won't be preserved
Samples
import kotlin.test.*
fun main() {
//sampleStart
val sequence = generateSequence(1) { it + 1 }
val windows = sequence.windowed(size = 5, step = 1)
println(windows.take(4).toList()) // [[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]]
val moreSparseWindows = sequence.windowed(size = 5, step = 3)
println(moreSparseWindows.take(4).toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10, 11], [10, 11, 12, 13, 14]]
val fullWindows = sequence.take(10).windowed(size = 5, step = 3)
println(fullWindows.toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8]]
val partialWindows = sequence.take(10).windowed(size = 5, step = 3, partialWindows = true)
println(partialWindows.toList()) // [[1, 2, 3, 4, 5], [4, 5, 6, 7, 8], [7, 8, 9, 10], [10]]
//sampleEnd
}
Returns a list of results of applying the given transform function to an each list representing a view over the window of the given size sliding along this collection with the given step.
Note that the list passed to the transform function is ephemeral and is valid only inside that function. You should not store it or allow it to escape in some way, unless you made a snapshot of it. Several last lists may have fewer elements than the given size.
Both size and step must be positive and can be greater than the number of elements in this collection.
Since Kotlin
1.2Parameters
the number of elements to take in each window
the number of elements to move the window forward by on an each step, by default 1
controls whether or not to keep partial windows in the end if any, by default false
which means partial windows won't be preserved
Samples
import kotlin.test.*
fun main() {
//sampleStart
val dataPoints = sequenceOf(10, 15, 18, 25, 19, 21, 14, 8, 5)
val averaged = dataPoints.windowed(size = 4, step = 1, partialWindows = true) { window -> window.average() }
println(averaged.toList()) // [17.0, 19.25, 20.75, 19.75, 15.5, 12.0, 9.0, 6.5, 5.0]
val averagedNoPartialWindows = dataPoints.windowed(size = 4, step = 1).map { it.average() }
println(averagedNoPartialWindows.toList()) // [17.0, 19.25, 20.75, 19.75, 15.5, 12.0]
//sampleEnd
}