Any enumerable that produces elements one by one during an enumeration is called a stream. Streams are composable and lazy enumerables.
Note: Streams do not operate unless it is needed.
Streams are lazy because they apply transformations to the enumerable elements and store computations. So, when we run the stream, elements go one by one through those computations.
Streams do not save all their contents in the memory. Instead, they produce data items one by one and pass them along when needed to be altered or transformed. They utilize a buffer for storing data until some other process requires it.
To store the results, treat it as a collection and pass it to a function in the
Let’s look at the below illustration:
Streams build a series of computations that are invoked only when we pass the underlying stream to the
Enum module. After that, we get the result stored in the stream.
range = 1..5 stream = Stream.map(range, &(&1 * 2)) stream = Enum.map(stream, &(&1 + 1)) IO.puts("The Result of the Stream is as Follows") IO.inspect stream
Line 2: We define the range and map it on the
stream using some operation
&(&1 * 2).
Line 3: We again map the
enum and operation
&(&1 + 1).
Line 5: We store the result in-stream and print it.
View all Courses