Sequences let you work with lists of items one by one without making a big list all at once. This saves memory and can be faster.
0
0
Sequence creation methods in Kotlin
Introduction
When you want to process a large list of numbers without using too much memory.
When you want to create a list of values that are calculated on the fly.
When you want to generate an infinite list of items and take only some of them.
When you want to chain many operations like filtering and mapping without creating intermediate lists.
Syntax
Kotlin
val sequence = sequenceOf(item1, item2, item3) val sequence = generateSequence(seed) { nextValue } val sequence = (start..end).asSequence()
sequenceOf creates a sequence from given items.
generateSequence creates a sequence by starting from a seed and generating next items until null.
You can convert ranges or collections to sequences using asSequence().
Examples
This creates a sequence with four numbers.
Kotlin
val seq1 = sequenceOf(1, 2, 3, 4)
This creates an infinite sequence starting at 1 and adding 1 each time.
Kotlin
val seq2 = generateSequence(1) { it + 1 }
This converts the range 1 to 5 into a sequence.
Kotlin
val seq3 = (1..5).asSequence()
Sample Program
This program creates a sequence of odd numbers starting at 1, takes the first 5, and prints them as a list.
Kotlin
fun main() { val seq = generateSequence(1) { it + 2 } // odd numbers starting at 1 val firstFive = seq.take(5).toList() println(firstFive) }
OutputSuccess
Important Notes
Sequences are lazy, so they only calculate items when needed.
Use toList() or similar to get a real list from a sequence.
Infinite sequences must be limited with operations like take() to avoid endless loops.
Summary
Sequences help process items one by one without storing all at once.
You can create sequences from items, ranges, or by generating values.
Sequences are lazy and efficient for big or infinite data.