Introduction
Sequences and collections help you handle groups of data. Knowing their performance helps you choose the best one for your task.
val mySequence = sequenceOf(1, 2, 3) val myList = listOf(1, 2, 3)
val numbers = listOf(1, 2, 3, 4, 5) val doubled = numbers.map { it * 2 }
val numbersSeq = sequenceOf(1, 2, 3, 4, 5) val doubledSeq = numbersSeq.map { it * 2 }
val result = numbersSeq.filter { it % 2 == 0 }.toList()
import kotlin.system.measureTimeMillis fun main() { val numbers = (1..1_000_000).toList() val timeList = measureTimeMillis { val doubled = numbers.map { it * 2 } val filtered = doubled.filter { it % 3 == 0 } println("List result size: ${filtered.size}") } val numbersSeq = numbers.asSequence() val timeSeq = measureTimeMillis { val doubledSeq = numbersSeq.map { it * 2 } val filteredSeq = doubledSeq.filter { it % 3 == 0 }.toList() println("Sequence result size: ${filteredSeq.size}") } println("List time: $timeList ms") println("Sequence time: $timeSeq ms") }
Sequence over a Collection in Kotlin when working with large datasets?asSequence() converts a collection to a sequence lazily.sequenceOf() creates a sequence from given elements, not a list; toSequence() and Sequence() constructor do not exist.val numbers = (1..5).asSequence()
.map { it * 2 }
.filter { it > 5 }
.toList()
println(numbers)val list = listOf(1, 2, 3, 4, 5)
val seq = list.asSequence()
val result = seq.map { it * 2 }
println(result)map returns a sequence but does not execute immediately.result prints the sequence object, not the transformed data, because no terminal operation like toList() was called.map operation is not executed because sequences are lazy. -> Option Bage > 30, then map to names, and finally collect the first 10 names. Which approach is best for performance?Pass the test and this pattern moves unknown