Anyone can help me pointing out the difference between the use of asSequence() in the following piece of code.
val numbers = 1 .. 50
val output = numbers.filter{ it < 10 }.map{ Pair("Kotlin", it)}
output.forEach(::println)
Adding asSequence()
val numbers = 1 .. 50
val output = numbers.asSequence().filter{ it < 10 }.map{ Pair("Kotlin", it)}
output.forEach(::println)
Creates a Sequence instance that wraps the original array returning its elements when being iterated. Creates a Sequence instance that wraps the original collection returning its elements when being iterated. Creates a Sequence instance that wraps the original map returning its entries when being iterated.
Kotlin sequences have many more processing functions (because they are defined as extension functions) and they are generally easier to use (this is a result of the fact that Kotlin sequences were designed when Java streams was already used — for instance we can collect using toList() instead of collect(Collectors.
The order of operations execution is different as well: Sequence performs all the processing steps one-by-one for every single element. In turn, Iterable completes each step for the whole collection and then proceeds to the next step.
The difference is that when you use a Sequence
it will only run the functions if you iterate over the elements. So for example this:
val numbers = 1 .. 50
val output = numbers.asSequence().filter{
println("Filtering $it")
it < 10
}.map{
println("Mapping $it")
Pair("Kotlin", it)
}
will print nothing, because you did not iterate over output
.
Checking the docs helps:
/**
* Creates a [Sequence] instance that wraps the original collection
* returning its elements when being iterated.
*/
public fun <T> Iterable<T>.asSequence(): Sequence<T> {
return Sequence { this.iterator() }
}
Using Sequence
s is useful because if you just call map
on a Collection
the result will be converted to a List
and with a Sequence
you can avoid these conversion steps. Think about Sequence
s like Stream
s in the Java Stream API (with the difference that Kotlin's solution does not support parallel execution).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With