![]() ![]() Order of transformations matters - avoid unnecessary workīecause terminal operations can finish processing early, and intermediate operations are evaluated lazily, sequences can, in some cases, help you avoid doing unnecessary work compared to collections. When working with sequences no intermediate collection is created and since items are evaluated one by one, map is only performed on some of the inputs. Since the condition from first is satisfied by the 2nd element, then we no longer apply the map on the rest of the collection. We iterate through the initial collection applying map and then first on each of them. first is called - this is a terminal operation, so, all the intermediate operations are triggered, on each element of the 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.asSequence - a sequence is created based on the Iterator of the original collection.first is called - we iterate through each item until the first square is found. ![]() 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. map is called - a new ArrayList is created.Let’s see how and when each operation is applied for collections and when for sequences Collections Make sure you check them out, before implementing your own version of these. Independent on whether you’re using collections or sequences, the Kotlin Standard Library offers quite a wide range of operations for both, like find, filter, groupBy and others. For example, looking at how map is implemented, we can see that it’s an inline function, that creates a new ArrayList: public inline fun Iterable.map(transform: (T) -> R): List The transformations on collections are inline functions. ![]() The difference between eager and lazy evaluation lies in when each transformation on the collection is performed.Ĭollections are eagerly evaluated - each operation is performed when it’s called and the result of the operation is stored in a new collection. ![]()
0 Comments
Leave a Reply. |