Kotlin Sequences
A Sequence is a lazily evaluated view of a collection that combines multiple operations into a single pass, avoiding the creation of many intermediate collections.
Collection filter and map create a new list on every call, wasting memory and time with large data; a sequence, by contrast, lets elements flow through the entire operation chain one by one.
This chapter explains the difference between sequences and collections, how to create a sequence, and in which scenarios it is worth switching to one.
What is a sequence
A sequence is represented by the interface Sequence which promises just one thing: it can produce elements one at a time.
Unlike List and Set, a sequence doesn't store elements itself; it stores the rule for "how to compute the next element".
Example
fun main
(
)
{
// A plain list
val list
=
listOf
(
"runoob"
,
"RUNOOB"
,
"kotlin"
)
// asSequence() wraps the list into a sequence; no computation happens at this point
val sequence
=
list.
asSequence
(
)
// Elements are actually processed only when a terminal operation is called
println
(
sequence.
first
(
)
)
println
(
sequence.
count
(
)
)
}
runoob
3
Tip:A sequence isn't a new data structure; it's more like a "processing pipeline" wrapped around a collection, where the steps run only when you actually request the result.
Differences between sequences and collections
Collection operations are eager: each function runs completely and returns a new collection.
Sequence operations are lazy: intermediate operations only record steps, and the terminal operation triggers the computation.
| Comparison Item | Collections (Iterable) | Sequences (Sequence) |
|---|---|---|
| Evaluation timing | Eager evaluation; every operation runs | Lazy evaluation; only the terminal operation runs |
| Intermediate results | Each step creates a new collection | No intermediate collections; elements flow through one by one |
| Number of passes | Each operation traverses once | All operations combined into a single pass |
| Can it be infinite | No; elements must first be loaded into memory | Yes; use take to grab a finite portion |
| Performance with small data | Faster; no extra wrapping overhead | Slightly slower; extra iterator and lambda overhead |
| Applicable scenarios | Few elements, or multiple traversals needed | Many elements, or operations that terminate early |
The example below applies the same chain of operations to a collection and a sequence, using a counter to record how many times the lambda actually runs.
Example
fun main
(
)
{
val data
=
(
1
..
10
)
.
toList
(
)
var listSteps
=
0
// Collection: filter first goes through all 10 elements, then map goes through the 5 even numbers
val listResult
=
data
.
filter
{
listSteps
++;
it
%
2
==
0
}
.
map
{
listSteps
++;
it
it
}
.
first
{
it
20
}
var seqSteps
=
0
// Sequence: each element passes through filter and map in turn, stopping immediately when the first matching element is found
val seqResult
=
data.
asSequence
(
)
.
filter
{
seqSteps
++;
it
%
2
==
0
}
.
map
{
seqSteps
++;
it
it
}
.
first
{
it
20
}
println
(
"Collection result: $listResult, lambda executions: $listSteps"
)
println
(
"Sequence result: $seqResult, lambda executions: $seqSteps"
)
}
集合结果:36,lambda 执行次数:15
序列结果:36,lambda 执行次数:9
The results are the same, but the collection ran the lambda 15 times while the sequence ran it only 9, because the sequence stopped processing after obtaining 36.
Creating a sequence
There are four common ways to create a sequence, each suited to a different data source.
| Method | Purpose | Example |
|---|---|---|
| sequenceOf | Create a sequence from a known set of elements | sequenceOf("runoob", "RUNOOB") |
| asSequence | Convert an existing collection or array into a sequence | listOf(1, 2).asSequence() |
| generateSequence | Generate a sequence from a seed and a "next value" rule; it can be infinite | generateSequence(1) { it * 2 } |
| sequence { } | Produce elements manually with yield, suitable for complex logic | sequence { yield(1) } |
Example
fun main
(
)
{
// 1. sequenceOf: the most direct option when elements are known
println
(
sequenceOf
(
"runoob"
,
"RUNOOB"
,
"kotlin"
)
.
toList
(
)
)
// 2. generateSequence: seed 1, multiply by 2 each time; this is an infinite sequence
val powers
=
generateSequence
(
1
)
{
it
2
}
println
(
powers.
take
(
5
)
.
toList
(
)
)
// Add takeWhile to stop when a condition is met
println
(
generateSequence
(
1
)
{
it
2
}
.
takeWhile
{
it
<=
100
}
.
toList
(
)
)
// 3. sequence { }: produce elements one by one with yield, suitable for stateful logic
val fib
=
sequence
{
var a
=
0
var b
=
1
while
(
true
)
{
// An infinite loop; use an external take to control how many are taken
yield
(
a
)
// Produce a value and pause, resuming on the next iteration
val next
=
a
b
a
=
b
b
=
next
}
}
println
(
fib.
take
(
8
)
.
toList
(
)
)
}
[runoob, RUNOOB, kotlin]
[1, 2, 4, 8, 16]
[1, 2, 4, 8, 16, 32, 64]
[0, 1, 1, 2, 3, 5, 8, 13]
Note:
sequence { }The code block is a suspend function; inside it you can only callyield、yieldAllsuspend functions provided by SequenceScope, and cannot directly call other suspend functions. This builder has been available since Kotlin 1.3.
Using Iterator.asSequence() A sequence obtained by wrapping can only be traversed once; a second traversal throws an exception; to prevent misuse you can call constrainOnce()(since Kotlin 1.3) to explicitly mark it as one-shot.
Intermediate and terminal operations
Functions on sequences fall into two categories: intermediate operations return a new sequence, while terminal operations return a concrete result and trigger computation.
Intermediate operations only record steps and don't execute immediately; this is the source of "laziness".
| Category | Common functions | Return Value |
|---|---|---|
| Intermediate operations | filter、map、mapNotNull、flatMap、take、drop、distinct、sorted、onEach | A new Sequence |
| Terminal operations | toList、toSet、first、find、count、sum、any、all、forEach、joinToString | A concrete value or collection |
Example
fun main
(
)
{
// This chain is merely "described"; no elements have been processed yet
val pipeline
=
sequenceOf
(
1
,
2
,
3
,
4
,
5
,
6
)
.
filter
{
println
(
"filter $it"
)
;
it
%
2
==
0
}
.
map
{
println
(
"map $it"
)
;
it
10
}
println
(
"--- No output yet ---"
)
// toList() is a terminal operation; only now do elements flow through filter and map one by one
val result
=
pipeline.
toList
(
)
println
(
result
)
}
--- No output yet up to this point ---
filter 1
filter 2
map 2
filter 3
filter 4
map 4
filter 5
filter 6
map 6
[20, 40, 60]
From the output order you can see that a sequence processes "one element through the whole chain, then the next element", rather than "filter everything first, then map everything".
Note:
sorted、sortedBy、groupByIntermediate operations that need to see all elements before producing a result read the entire sequence into memory first, so they cannot be used directly on infinite sequences.
Performance comparison example
The advantage of sequences is most obvious when the data is large and there is an early-termination condition.
The example below performs the same filter over 5 million elements and takes only the first result that satisfies the condition.
Example
import
kotlin.system.measureTimeMillis
fun main
(
)
{
val data
=
(
1
..
5
_000_000
)
.
toList
(
)
// Collection: filter and map each create an intermediate list of about 1.67 million elements
val listTime
=
measureTimeMillis
{
data.
filter
{
it
%
3
==
0
}
.
map
{
it
2
}
.
first
{
it
1
_000
}
}
// Sequence: stops immediately after finding the first matching element, allocating almost no extra memory
val seqTime
=
measureTimeMillis
{
data.
asSequence
(
)
.
filter
{
it
%
3
==
0
}
.
map
{
it
2
}
.
first
{
it
1
_000
}
}
println
(
"Collection time: ${listTime}ms"
)
println
(
"Sequence time: ${seqTime}ms"
)
}
集合耗时:96ms
序列耗时:2ms
Tip:The timings above are example values from one run; actual numbers vary with machine performance, but the order-of-magnitude gap between the two is stable.
When to use a sequence
A sequence is not a silver bullet for performance; with small data it is actually slower because it introduces iterator and lambda-call overhead for every element.
| Scenario | Recommend | Reason |
|---|---|---|
| Very few elements (a few dozen or fewer) | Union | No burden of intermediate collections; direct traversal is faster |
| Large data with many chained operations | Sequence | Avoid creating multiple huge intermediate collections |
| The chain includes early-terminating operations like first, find, take, any | Sequence | Stop as soon as you get the result; no need to process the remaining elements |
| Need an infinite or unknown-length data stream | Sequence | A collection cannot hold infinite data |
| Need to traverse the same data multiple times | Union | A sequence recomputes on every terminal operation |
| Need random access or index-based lookup | Union | A sequence can only be iterated sequentially; it does not support indexing |
A practical rule of thumb: if the terminal operation of the chain is toList() and the number of elements is small, just use a collection; if the chain ends with first()、take()、find() or the data is large, switching to a sequence is usually more worthwhile.
Common questions
Here are some typical questions about using sequences.
| Problem | Reason | Solution |
|---|---|---|
| Wrote a sequence operation but got no output | You only wrote intermediate operations and didn't call a terminal operation | Add a terminal operation such as toList, forEach, or count |
| A sequence throws an error on the second traversal | A sequence wraps an Iterator and can only be traversed once | Call asSequence again, or declare explicitly with constrainOnce |
| Getting stuck or memory ballooning after sorted | Sorting is a stateful operation that needs to read the whole sequence | Don't use it on infinite sequences; use take to limit the range first |
| Switching a small list to a sequence is actually slower | Sequences have extra wrapping and scheduling overhead | With small data, keep using collections |
| Calling a regular suspend function inside a sequence block throws an error | SequenceScope only allows suspend calls from the yield family | Write the logic as a regular function, then yield the result inside the block |