Sequence
- Kotlin course
- Expert
- Lesson 40/47
- 5 min
Learn lazy computation optimization with Sequence.
What is a Sequence?
A Sequence is a lazily evaluated stream in Kotlin. Each step runs only when the result is needed; no intermediate collection is created.
Example: (1..10).asSequence().map { it * 2 }.filter { it > 5 }.toList(). With List every step creates a new list; a Sequence computes in a single pass. This lowers both allocation and time on large data. The seqInfo model in this lesson shows the concept.
Sequence versus List
List creates a new collection at every step (eager). Sequence processes only as many elements as needed in a single pass (lazy).
For example (1..3).asSequence().map { it * 2 }.joinToString() yields "2, 4, 6"; no intermediate list is created. The difference is small on tiny data; on millions of elements Sequence saves both memory and time. A terminal operation (toList, joinToString) is needed to reach the result.
Practice Write seqInfo
Define fun seqInfo(): String. Its body should return (1..3).asSequence().map { it * 2 }.joinToString(). In main, write println(seqInfo()).
Starter code
// add the seqInfo function
fun main() {
// print the seqInfo result
}Sample solution
fun seqInfo(): String = (1..3).asSequence().map { it * 2 }.joinToString()
fun main() {
println(seqInfo())
}Expected output
2, 4, 6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What kind of computation does a Sequence do?
A Sequence does deferred computation.- Eager
- Lazy Correct answer
- Asynchronous
- Parallel
Explanation: A Sequence is evaluated lazily.
2 Complete the asSequence call
val s = (1..10).____()
val s = (1..10).asSequence()
Explanation: asSequence() turns a range into a lazy stream.
3 Match the Sequence parts
| Term | Meaning |
|---|---|
Sequence |
Lazy stream |
asSequence |
Converter |
lazy |
Deferred |
joinToString |
Terminal op |