Image source: https://kotlinlang.org/

Kotlin Collections vs Sequences in 2 minutes

Monika Kumar Jethani
ProAndroidDev
Published in
2 min readMay 23, 2021

--

Let’s understand the difference between Collections and Sequences with a simple example,

val operations = (1..10)
.filter{it % 2 == 1}
.map { it * 2 }
.take(2)

Collections

In the above collection operations, we will first loop through numbers from 1 to 10, then create a collection of numbers who are odd, then create another collection by multiplying the elements of previous collection by 2 and then create a collection by taking first 2 elements of previous collection.

Putting down the list of operations,

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Operation 1 — filter — 1, 3, 5, 7, 9 //new collection

Operation 2— map — 2, 6, 10, 14, 18 //new collection

Operation 3 — take — 2, 6 //new collection

So, collections are,

1- Evaluated eagerly.

2- Each transformation is performed on the entire collection.

3- A new collection gets created after applying transformation on the initial collection.

4- Suitable for smaller lists, not for larger ones as processing intermediate collection equation becomes expensive.

Sequences

Now, let’s understand the above through sequences.

We can convert a collection to sequence using the asSequence() function, so the above code can be written as,

val operations = (1..10).asSequence()
.filter{it % 2 == 1}
.map { it * 2 }
.take(2)
.toList()

In the above sequence, we will first loop through numbers from 1 to 10, then look at each element one by one, then put the filter transformation, which is an an intermediate operation into the list of operations to be performed by the sequence, but the filter operation isn’t performed, same for map operation, once we encounter the terminal operation, which is ‘take’ operator in this case, all the transformations are applied

Putting down the results,

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

1 -> filter — 1, map — 2, take — result — 1

2 -> filter — no result

3 -> filter — 3, map — 6, take — result — 3

So, sequences are,

1- Evaluated lazily.

2- Each transformation is performed on the elements one-by-one.

3- No new collection is created.

4- Suitable for larger lists.

--

--