The windowed() extension function in Kotlin returns a list of snapshots of the window of the given size sliding along this set with the given step. It can also return a list of results of applying the given transform function to each list representing a view over the window.
There are 2 variations for the syntax of Set.windowed() extension function. They are:
fun <T> Set<T>.windowed(size: Int, step: Int = 1, partialWindows: Boolean = false): List<List<T>>
This extension function returns a list of snapshots of the window of the given size sliding along this set with the given step, where each snapshot is a list.
Returns value of type List<List<T>>
.
fun <T, R> Set<T>.windowed(size: Int, step: Int = 1, partialWindows: Boolean = false, transform: (List<T>) -> R): List<R>
This extension function returns a list of results of applying the given transform function to each list representing a view over the window of the given size sliding along this set with the given step.
Returns value of type List<R>
.
Using windowed() to create a sliding window of size 3 with step 1.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val windows = numbers.windowed(size = 3)
println(windows)
}
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
Using windowed() to create a sliding window of size 2 with step 2, including partial windows.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val windows = numbers.windowed(size = 2, step = 2, partialWindows = true)
println(windows)
}
[[1, 2], [3, 4], [5]]
Using windowed() with a transform function to create a sliding window of size 3 and compute the sum of each window.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val windowSums = numbers.windowed(size = 3) { it.sum() }
println(windowSums)
}
[6, 9, 12]
In this Kotlin tutorial, we learned about windowed() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.