Collections and Sequences in Kotlin

Tram Ho

Working with collections is a common task and the Kotlin Standard Library offers many great utility functions. It also provides two ways of working with collections based on how they value: eagerly – with Collections, and lazily – with Sequences. Keep reading to find out what is the difference between them, what you should use and when, and what the performance meaning of each is.

Collections vs Sequences

The difference between eager and lazy evaluation lies when each change on the collection is done.

Collections are evaluated as eager – each operation is performed when it is called and the result of the activity is stored in a new Collections. The transforms on Collections are inline functions.

For example, looking at how the map is implemented, we can see that it is inline function, creating a new ArrayList:

Sequences are rated lazy. It has two types of intermediate and terminal operations . Intermediate operation is not performed in place, it is only stored. Only when a terminal operation is called, the tintermediate operations are triggered on each successive element and finally, the terminal activity is applied. Intermediate operations (like map , distinct , groupBy , etc.) return another string while terminal operations (like first , toList , count , etc.)

Sequences do not hold a reference for Sequences items. They have been created based on the iterator of the original Sequences and hold a reference to all intermediate operations that need to be performed.

Unlike transformations on Collections, intermediate transformations on strings are not inline functions – inline functions cannot be stored and sequences need to store them.

A terminal operation, like first , iterates over the elements of the string until the predicate condition is matched.

If we look at how to execute the sequence like TransformingSequence (used in the map above), we will see that when the next is called on the sequence iterator, the stored transformation is also applied.

Regardless of whether or not you use collections or sequences, Kotlin Standard Library provides a range of activities for both, like find , filter , groupBy and others. Make sure you check them out, before making this version of your own.

Share the news now

Source : Viblo