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)
In the above collection operations, we 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.
For the above example with collections, the results at each step would be as follows:
val operations = (1..10)
.filter { it % 2 == 1 } // 1, 3, 5, 7, 9
.map { it * 2 } // 2, 6, 10, 14, 18
.take(2) // 2, 6
Now, let’s take a look at the map function for Collections.
#kotlin