Lazy Operations
Avoid intermediate lists.
Lazy Operations
The power of sequences comes from lazy operations. Intermediate operations build a pipeline without running it, and only a terminal operation pulls elements through. This avoids intermediate lists.
No Intermediate Lists
With collections, each map and filter allocates a new list. With sequences, elements stream through all steps without creating those temporary lists.
fun main() {
val result = (1..6).asSequence()
.map { it * it }
.filter { it % 2 == 0 }
.toList()
println(result)
}All lessons in this course
- Why Sequences
- Creating Sequences
- Lazy Operations
- Sequences vs Collections