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.
Syntax :
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.
Example :
object GFG
{
def main(args : Array[String])
{
val stream = 1 #:: 2 #:: 8 #:: Stream.empty
println(stream)
}
}
|
Output:
Stream(1, ?)
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.
Example :
import scala.collection.immutable.Stream.cons
object GFG
{
def main(args : Array[String])
{
val stream 2 : Stream[Int] = cons( 1 , cons( 2 , cons( 3 , Stream.empty) ) )
println(s "Elements of stream2 = ${stream2}" )
}
}
|
Output:
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.
Example :
object GFG
{
def main(args : Array[String])
{
val stream = 1 #:: 2 #:: 8 #:: Stream.empty
println(stream)
print( "Take first 2 numbers from stream = " )
stream.take( 2 ).print
print( "\nTake first 10 numbers from stream2 = " )
stream.take( 10 ).print
}
}
|
Output :
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.
Example :
object GFG
{
def main(args : Array[String])
{
val stream = 1 #:: 2 #:: 8 #:: Stream.empty
println(stream)
println(stream.map{ _ + 5 })
}
}
|
Output:
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.
Example :
object GFG
{
def main(args : Array[String])
{
val emptyStream : Stream[Int] = Stream.empty[Int]
println(s "Empty Stream = $emptyStream" )
}
}
|
Output:
Empty Stream = Stream()