Kotlin : Slow List and Lazy Sequence

Came from Java 7 into Kotlin, we are so happy that we could easily have Collection operators on List and chain them together. But little did we know List with it’s iterator is not the best thing still (for some case), there another thing call Sequence.

A little background on List, the hard worker.

Before we get into telling why Sequence is better (in some case), let me tell you something about List.

List is operated with Iterator. It is a very hardworking bunch, where each operation I chain to it, it will ensure it is done.

val list = listOf(1, 2, 3, 4, 5, 6)
list.map{ it * 2 }.filter { it % 3 == 0 }.average()

As you see in the illustration above, for every step, each of the items is processed fully.

To proof this, let’s log out something

val list = listOf(1, 2, 3, 4, 5, 6)
val result = list
.map{ println("In Map"); it * 2 }
.filter { println("In Filter");it % 3 == 0 }
println("Before Average")
println(result.average())

--

--