A Kotlin Sequence represents elements that can be enumerated one at a time. Use it when a chain of collection operations would otherwise create temporary lists, especially for large inputs or when a later operation can stop early. Sequence operations use familiar functions such as map and filter, but defer work until a result is requested. section 6.2 section 6.3
Convert a collection to a lazy pipeline
```kotlin val names = people .asSequence() .map(Person::name) .filter { it.startsWith("A") } .toList() ``` asSequence() changes the collection pipeline into a Sequence. map and filter return further sequences rather than intermediate lists; toList() is the terminal operation that obtains the final list. The result matches the eager collection version while avoiding temporary collections between steps. section 6.2
Sequence operations are intermediate or terminal. Intermediate operations describe transformations and remain lazy. A terminal operation produces a collection, element, number, or other result and triggers the postponed work. Processing is element-by-element: an element is mapped and then filtered before the next element is considered, unlike eager collection chains that complete one operation across the whole collection first. section 6.2.1
Stop when a result is found
```kotlin val firstSquareOver3 = listOf(1, 2, 3, 4) .asSequence() .map { it * it } .find { it > 3 } // 4 ``` find is terminal, so evaluation begins only there. Once 2 is squared to 4 and matches the predicate, later elements need not be processed. Put filters before costly transformations when filtering can reduce the work performed. section 6.2.1 section 6.2.1
Generate a sequence instead of starting with a collection
```kotlin val naturalNumbers = generateSequence(0) { it + 1 } val total = naturalNumbers .takeWhile { it <= 100 } .sum() // 5050 ``` generateSequence supplies an initial value and a rule for the next value. It can describe an infinite sequence; takeWhile bounds it, and sum triggers evaluation. The same pattern can traverse parent directories and stop when a hidden directory is found. section 6.2.2 section 6.2.2
Laziness is not automatically faster. Sequences avoid intermediate collections, but their intermediate objects and non-inlined lambdas add overhead. Prefer them when large collections or short-circuiting make that trade-off worthwhile; ordinary collection operations remain suitable for smaller chains. section 10.2.3





















