Sequences
suggest changeIn Kotlin, standard collection processing (List, Set, Map) executes eagerly: each intermediate operation (filter, map, flatMap) creates and populates a new intermediate collection in memory.
Sequence<T> provides lazy evaluation: elements are processed one-by-one through the entire pipeline only when a terminal operation is called. This eliminates intermediate allocations and enables short-circuiting on large or infinite data streams.
Collections vs Sequences
Consider an operation finding the first square of an even number greater than 10:
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
// Eager Collection Processing:
// 1. filter creates a new 5-element list: [2, 4, 6, 8, 10]
// 2. map creates another 5-element list: [4, 16, 36, 64, 100]
// 3. first finds 16
val eagerResult = numbers
.filter { it % 2 == 0 }
.map { it * it }
.first { it > 10 }
// Lazy Sequence Processing:
// Evaluates element-by-element:
// - 1 -> filtered out
// - 2 -> 2 * 2 = 4 (not > 10)
// - 3 -> filtered out
// - 4 -> 4 * 4 = 16 (matches > 10! stops processing remaining items)
val lazyResult = numbers.asSequence()
.filter { it % 2 == 0 }
.map { it * it }
.first { it > 10 }
In the sequence version, elements 5 through 10 are never inspected or mapped.
Creating Sequences
1. From Existing Collections
Convert any Iterable to a Sequence using .asSequence():
val namesSequence = listOf("Alice", "Bob", "Charlie", "David").asSequence()
2. Using sequenceOf()
val directSeq = sequenceOf("red", "green", "blue", "yellow")
3. Using generateSequence
generateSequence creates sequences dynamically. If the step lambda returns null, the sequence terminates:
// Generating an infinite sequence of powers of 2
val powersOfTwo = generateSequence(1) { it * 2 }
println(powersOfTwo.take(5).toList()) // [1, 2, 4, 8, 16]
// Generating a terminating sequence (e.g. countdown)
val countdown = generateSequence(5) { if (it > 1) it - 1 else null }
println(countdown.toList()) // [5, 4, 3, 2, 1]
4. Using the sequence { } Builder (Yield)
The sequence { } builder allows generating elements imperatively with yield() and yieldAll(). Execution suspends after each yield until the next item is pulled:
val fibonacci = sequence {
var terms = Pair(0L, 1L)
while (true) {
yield(terms.first)
terms = Pair(terms.second, terms.first + terms.second)
}
}
fun main() {
val first10Fib = fibonacci.take(10).toList()
println(first10Fib) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
}
Sequence Operations
Operations on sequences fall into two categories:
-
Intermediate Operations (Lazy): Return a new
Sequence. No processing occurs when these are called.- Filtering:
filter,filterNot,take,drop,distinct - Mapping:
map,mapNotNull,flatMap - Sorting / Chunking:
sortedBy,chunked,windowed
- Filtering:
-
Terminal Operations (Eager): Trigger the actual computation pipeline and produce a result or collection.
- Accumulating:
toList(),toSet(),toCollection(...) - Searching:
first(),firstOrNull(),find(),single() - Aggregating:
count(),sum(),average(),reduce(),fold() - Consuming:
forEach { ... }
- Accumulating:
val result = sequenceOf("apple", "banana", "cherry", "avocado", "apricot")
.filter { it.startsWith("a") }
.map { it.uppercase() }
.sorted() // Note: sorted() requires buffering all upstream items
.take(2)
.toList() // Terminal operation triggers evaluation
println(result) // [APPLE, APRICOT]
Sequence State and Multi-Iteration
Certain sequences can only be iterated once (e.g. sequences wrapping a network stream or single-use generator). Calling a terminal operation a second time throws an IllegalStateException:
val seq = generateSequence { readlnOrNull() }
// Safe: convert to a List if multi-pass iteration is required
val items = seq.takeWhile { it.isNotBlank() }.toList()
When to Use Sequences vs Collections
| Scenario | Use Collections | Use Sequences |
|---|---|---|
| Small datasets (< 1,000 items) | Yes (less allocation overhead) | No |
| Large datasets (> 100,000 items) | No (huge intermediate garbage) | Yes (zero intermediate lists) |
Short-circuiting (first, any, take) |
No (processes all items first) | Yes (stops evaluation early) |
Single operation (only .filter or .map) |
Yes (direct loop without wrappers) | No |
| Infinite streams (generators) | Impossible (OutOfMemoryError) | Yes |
Best Practices
- Convert to List at the Edge: Keep internal transformations lazy with
Sequence<T>, but return concreteList<T>orSet<T>from public APIs to prevent repeated deferred re-evaluation by callers. - Order Operations for Early Pruning: Place
filter,take, anddistinctbefore expensivemapoperations in the sequence pipeline to minimize transformation overhead. - Be Cautious with State-Buffering Operations: Operations like
sorted()must consume and buffer all preceding elements in memory before producing their first element, partially reducing the streaming benefits of a sequence.distinct()still streams, but remembers every element it has seen.