Sequence
is a Kotlin class that works a lot like List
. However, it
has a major difference in how its standard higher-order functions, like
map()
and filter()
, work.
With a List
, higher-order functions mostly work on the entire list contents
at a time. With a Sequence
, each item is processed individually.
This is particularly useful for longer collections, where the chain
of higher-order functions can "short circuit" excessive work.
One way to get a Sequence
is to use sequenceOf()
, which works like
listOf()
except that it creates a Sequence
.
If this snippet used listOf()
, map()
would first process all items
in the List
to generate its result, then filter()
would process all
the items from the map()
output, then firstOrNull()
would process all
the items up until its lambda expression returned true
.
Since we are using sequenceOf()
, map()
emits the first item, which
filter()
then processes (and rejects, since it is not even). map()
then emits the second item, which filter()
passes, and that causes
firstOrNull()
to return true
(since the ID is negative). As a result,
neither map()
, nor filter()
, nor firstOrNull()
need to deal with
any of the other items in the Sequence
. This can save a lot of processing
time.