Android Developers
Published in

Android Developers

Collections vs sequences

Collections and sequences in Kotlin

Collections vs sequences

public inline fun <T, R> Iterable<T>.map(transform: (T) -> R): List<R> {
return mapTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
public fun <T, R> Sequence<T>.map(transform: (T) -> R): Sequence<R>{      
return TransformingSequence(this, transform)
public inline fun <T> Sequence<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException(“Sequence contains no element matching the predicate.”)
internal class TransformingIndexedSequence<T, R> 
constructor(private val sequence: Sequence<T>, private val transformer: (Int, T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {

override fun next(): R {
return transformer(checkIndexOverflow(index++),


Collections and sequences

Collections vs sequences


  • map is called — a new ArrayList is created. We iterate through all items of the initial collection, transform it by copying the original object and changing the color, then add it to the new list.
  • first is called — we iterate through each item until the first square is found


  • asSequence — a sequence is created based on the Iterator of the original collection
  • map is called — the transformation is added to the list of operations needed to be performed by the sequence but the operation is NOT performed
  • first is called — this is a terminal operation, so, all the intermediate operations are triggered, on each element of the collection. We iterate through the initial collection applying map and then first on each of them. Since the condition from first is satisfied by the 2nd element, then we no longer apply the map on the rest of the collection.
Collections vs sequences — eager vs lazy evaluation


Order of transformations

Order of transformations matters — avoid unnecessary work

Inlining and large data sets consequences



Articles on modern tools and resources to help you build experiences that people love, faster and easier, across every Android device.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store