The Stream is a lazy lists where elements are evaluated only when they are needed. This is a scala feature. Scala supports lazy computation. It increases performance of our program. Streams have the same performance characteristics as lists.
val str = 1 #:: 2 #:: 3 #:: Stream.empty
In scala a List can be constructed with :: operator, whereas a Stream can be constructed with the #:: operator method, using
Stream.empty at the end of the expression. In above syntax the head of this stream is 1, and the tail of it has 2 and 3.
Operations on Stream
Create a Stream: Below is the examples to create a streams in Scala.
In the above output, we can see that second element is not evaluated. Here, a question mark is displayed in place of element. Scala does not evaluate list until it is required. The tail is not printed, because it hasn’t been computed yet. Streams are specified to lazy computation.
Create a Stream using Stream.cons : We can also create a Stream by using Stream.cons . A package
import scala.collection.immutable.Stream.cons is used for creating stream.
Elements of stream2 = Stream(1, ?)
Using take function on stream: take function is used to take elements from stream. Below is the example of using take function.
Stream(1, ?) Take first 2 numbers from stream = 1, 2, empty Take first 10 numbers from stream2 = 1, 2, 8, empty
When we wanted to take 10 numbers from a Stream, although it only contained 3 elements, it did not throw any IndexOutOfBoundsException.
Using map function on stream: map function is used to perform operation on stream.
Stream(1, ?) Stream(6, ?)
In above example by using map function we are transforming the input collection to a new output collection.
Initialize an empty Stream: Below code shows how to initialize an empty Stream.
Empty Stream = Stream()