Kotlin Set windowed()
Syntax & Examples


Set.windowed() extension function

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.


Syntax of Set.windowed()

There are 2 variations for the syntax of Set.windowed() extension function. They are:

1.
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>>.

2.
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>.



✐ Examples

1 Sliding window of size 3 with step 1

Using windowed() to create a sliding window of size 3 with step 1.

For example,

  1. Create a set of integers.
  2. Use windowed() to create a sliding window of size 3 with step 1.
  3. Print the resulting list of windows.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val windows = numbers.windowed(size = 3)
    println(windows)
}

Output

[[1, 2, 3], [2, 3, 4], [3, 4, 5]]

2 Sliding window of size 2 with step 2 including partial windows

Using windowed() to create a sliding window of size 2 with step 2, including partial windows.

For example,

  1. Create a set of integers.
  2. Use windowed() to create a sliding window of size 2 with step 2, including partial windows.
  3. Print the resulting list of windows.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val windows = numbers.windowed(size = 2, step = 2, partialWindows = true)
    println(windows)
}

Output

[[1, 2], [3, 4], [5]]

3 Transforming each window to its sum

Using windowed() with a transform function to create a sliding window of size 3 and compute the sum of each window.

For example,

  1. Create a set of integers.
  2. Use windowed() with a transform function to create a sliding window of size 3 and compute the sum of each window.
  3. Print the resulting list of sums.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val windowSums = numbers.windowed(size = 3) { it.sum() }
    println(windowSums)
}

Output

[6, 9, 12]

Summary

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.