Home » Scala

Streams in Scala

Scala | Streams: In this tutorial on streams in Scala, we will learn about streams in Scala which are special types of lists. Here, we will learn about them in detail with examples.
Submitted by Shivang Yadav, on April 10, 2020

Scala | Streams

Stream in Scala is a type of lazy val. It is a lazy val whose elements are evaluated only when they are used in the program. Lazy initialization is a feature of Scala that increases the performance of the program.

Syntax:

    val str = 1 #:: 2 #:: 3 #:: Stream.empty

Elements of a stream are created using #:: operator using Stream.empty at the end of initialization.

Program to show the creation of a stream

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val myStream =  2 #:: 4 #:: 6 #:: Stream.empty; 
		println("New Stream created...")
		println(myStream)
	} 
}

Output

New Stream created...
Stream(2, <not computed>)

Creating stream using stream.cons

You can create a stream using stream.cons. It will create an immutable stream and needs an import statement Scala.collection.immutable.Stream.cons.

import scala.collection.immutable.Stream.cons 

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
		val myStream: Stream[Int] = cons(2, cons(4, cons(6, Stream.empty)))
		println("New Stream created...")
		println(myStream)
	} 
}

Output

New Stream created...
Stream(2, <not computed>)

Accessing elements of the stream

In streams, take method is used to take/access elements.

Program to access elements using take method

import scala.collection.immutable.Stream.cons

object myObject 
{ 
	def main(args:Array[String]) 
	{ 
	    val myStream: Stream[Int] = cons(2, cons(4, cons(6, cons(9, Stream.empty))))
		print("Accessing Stream : ")
		print(myStream) 
		print("\nTake first 2 elements of stream : ") 
		myStream.take(2).print
		print("\nTake all elements from stream : ") 
		myStream.take(5).print
	} 
} 

Output

Accessing Stream : Stream(2, <not computed>)
Take first 2 elements of stream : 2, 4
Take all elements from stream : 2, 4, 6, 9

Creating an empty Stream

You can create an empty stream in Scala using Stream.empty.

object myObject 
{ 
    def main(args:Array[String]) 
    { 
        val myStream: Stream[Int] = Stream.empty[Int] 
        print("This is an empty Stream : ") 
        println(myStream)
    } 
} 

Output

This is an empty Stream : Stream()



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.