Say Hello to Kotlin Sequence
In some case, sequence operation is faster than collection operation.
val list1 = (1..10_000_000)
.filter { it % 2 == 0 }
.map { it * 10 }
.map { it.toString() }
.size // 5,000,000
// took 1,263 milliseconds in my environment
val list2 = (1..10_000_000)
.asSequence()
.filter { it % 2 == 0 }
.map { it * 10 }
.map { it.toString() }
.toList()
.size // 5,000,000
// took 1,015 milliseconds in my environment
In this case, you can create Sequence directly like this:
val list3 = generateSequence(1) { it + 1 }
.take(10_000_000)
.filter { it % 2 == 0 }
.map { it * 10 }
.map { it.toString() }
.toList()
.size // 5,000,000
// took 861 milliseconds in my environment
Sequence executes lazily and does not create intermediate products.
Sequence need some overhead, so be care it is not always faster than Collection.
About me 😎

茨城県つくば市在住のソフトウェアエンジニアです。専門領域はAndroidアプリ開発で、特にアーキテクチャに興味があります。某社でAndroidアプリ開発のテックリードをしています。
Jetpack ComposeによるAndroid MVVMアーキテクチャ入門の著者です。
👉 もっと詳しく
Writing 📝
Android MVVMアーキテクチャ入門
Androidアプリ開発の初学者に向けた、MVVM(Model-View-ViewModel)アーキテクチャの入門書を書きました。初学者の方を確実にネクストレベルに引き上げる技術書です。
👉 もっと詳しく