Junior — Middle
When is it preferable to use sequences instead of standard collections?
sobes.tech AI
Answer from AI
Sequences in Kotlin are lazy collections that compute elements on demand, unlike standard collections (List, Set), which usually compute all elements immediately.
It is preferable to use sequences when:
- You need to process a large or potentially infinite stream of data
- You perform a chain of operations (filtering, mapping, sorting), and want to avoid creating intermediate collections
- Performance and memory efficiency are important when processing data
Example:
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.asSequence()
.filter { it % 2 == 1 }
.map { it * it }
.toList()
println(result) // [1, 9, 25]
Here, filtering and mapping are performed lazily, without creating intermediate lists, which is efficient for large data.