Sequences in Kotlin collections.
Do you want to iterate over a huge collection [List] let`s find out how to do it?
If you try to Filter a list and get the final result you can do it like the code below →
data class Meeting(val id: Int, val title: String)
val meeting: List<Meeting> = listOf(Meeting(1, "HR"), Meeting(2, "Tech"))
val iterationTitle: List<String> = meeting
.filter {
println("Filter")
it.title.endsWith("h")
}
.map {
println("Map")
it.title
}
)
It will prints →
Filter
Filter
Map
Map
It will iterate over the list even if you don`t make any operations on the result list, will iterate over the list to Filter it then iterate again to Map it so, it will be a huge memory usage because it creates an intermediate list to hold the results but we can use Sequences instead.
--> lazily evaluated.
--> Evaluated starts when using terminal operation.
Check the code below you will find that we do not operate over the variable so it will not be evaluated.
val sequenceTitles: Sequence<String> = meeting
.asSequence()
.filter {
println("Sequance Filter")
it.title.endsWith("h")
}
.map {
println("Sequance Map")
it.title
}
But what will happen if we tried to iterate over the result.
for (seq in sequenceTitles) println(seq)
It will print like below -->
Sequence Filter.
Sequence Map.
And then prints the title.
That means it will iterate over every single item that matches the filter we need [Every processing step complete and return its result].
Conclusion:
Sequences perform processing step by step for every single item, Iteration performs the whole step for the collection then goes to the next step so Sequences avoids making intermediate steps however, the laziness of Sequences can make an overhead in small collections.
Hence, you should consider both Sequence and Iterable and decide which one is better for your case.
Reference --> Kotlin Docs