Lazy evaluation postpones collection computations until a result is requested. In Kotlin, sequences apply this strategy to chains of operations, avoiding intermediate collections and potentially skipping elements that never affect the result. section 6.2 section 6.2.1
people
.asSequence() #1
.map(Person::name) #2
.filter { it.startsWith("A") } #2
.toList() #3
Convert a collection with asSequence, compose familiar map and filter operations, then call toList to trigger evaluation and obtain a list. section 6.2
The sequence pipeline follows three practical rules:
- Intermediate operations such as map and filter return another sequence and execute lazily. section 6.2.1
- A terminal operation such as toList or find requests a result and triggers the postponed computations. section 6.2.1
- Sequence operations process each element through the pipeline before moving to the next, unlike collection operations that complete one operation across the collection first. section 6.2.1
- Ordering can reduce work: placing filter before map reduces the number of elements transformed. section 6.2.1
Finding without transforming everything
listOf(1, 2, 3, 4).asSequence().map { it * it }.find { it > 3 } returns 4. The sequence maps and tests elements in order, so processing can finish when the first matching result is found; an eager collection pipeline would map every element first. section 6.2.1
fun main() {
println(
listOf(1, 2, 3, 4)
.asSequence()
.map {
print("map($it) ")
it * it
}.filter {
print("filter($it) ")
it % 2 == 0
}
)
// kotlin.sequences.FilteringSequence@506e1b77
}
Printing a sequence before a terminal operation displays the sequence object rather than executing map and filter, making deferred evaluation visible. section 6.2.1












