Kotlin List windowed()
Syntax & Examples
Syntax of List.windowed()
There are 2 variations for the syntax of List.windowed() extension function. They are:
1.
fun <T> Iterable<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 collection with the given step, where each snapshot is a list.
2.
fun <T, R> Iterable<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 an each list representing a view over the window of the given size sliding along this collection with the given step.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing integers from 1 to 5. - We use the
windowed(3)
function to obtain snapshots of the window of size 3 sliding along the list. - Each snapshot is represented as a list within the
windows
list. - Finally, we print the
windows
list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val windows = list.windowed(3);
println(windows);
}
Output
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
2 Example
In this example,
- We create a list named
list
containing characters 'a' to 'e'. - We use the
windowed(2)
function to obtain snapshots of the window of size 2 sliding along the list. - Each snapshot is represented as a list within the
windows
list. - Finally, we print the
windows
list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val windows = list.windowed(2);
println(windows);
}
Output
[[a, b], [b, c], [c, d], [d, e]]
3 Example
In this example,
- We create a list named
list
containing strings "apple" to "elderberry". - We use the
windowed(4)
function to obtain snapshots of the window of size 4 sliding along the list. - Each snapshot is represented as a list within the
windows
list. - Finally, we print the
windows
list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val windows = list.windowed(4);
println(windows);
}
Output
[[apple, banana, cherry, date], [banana, cherry, date, elderberry]]
Summary
In this Kotlin tutorial, we learned about windowed() extension function of List: the syntax and few working examples with output and detailed explanation for each example.