Sequence
- Kotlin course
- Advanced
- Lesson 51/83
- 5 min
Learn lazy collections with Sequence.
Lazy sequences
A Sequence is a lazy collection stream. Operations are not applied until a terminal operation is called. This saves memory for large data.
Example: (1..10).asSequence().map { it * 2 }.filter { it > 10 }.toList(). Here map and filter are lazy; they execute only when toList is called. A Sequence creates no intermediate collections in long chains; this is efficient.
asSequence and terminal operations
asSequence() converts a collection into a Sequence. Nothing happens until a terminal operation (toList, sum, count) is called.
Example: val sum = (1..5).asSequence().map { it * 10 }.sum(). map is lazy; when sum is called, the whole chain runs and the result is 150. This pattern is efficient for large ranges; it builds no intermediate lists.
Practice Even squares with Sequence
In main assign the result of (1..5).asSequence().map { it * it }.filter { it % 2 == 0 }.toList() to a variable and print it with println.
Starter code
// in main convert the 1..5 range to a Sequence
// map to its square, filter the even ones, print with toListSample solution
fun main() {
val result = (1..5).asSequence()
.map { it * it }
.filter { it % 2 == 0 }
.toList()
println(result)
}Expected output
[4, 16]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the Sequence parts
| Term | Meaning |
|---|---|
asSequence() |
Convert to Sequence |
map { } |
Lazy transform |
filter { } |
Lazy filter |
toList() |
Terminal operation |
2 Which of these is a Sequence terminal operation?
- toList Correct answer
- map
- asSequence
- filter
Explanation: toList is a terminal operation; it runs the chain.
3 Complete the asSequence call
val sum = (1..5).____().map { it * 10 }.sum()
val sum = (1..5).asSequence().map { it * 10 }.sum()
Explanation: asSequence converts a collection into a Sequence.