Monday, 6 May 2019

Stack in Scala


Stack
A stack is a last-in, first-out (LIFO) data structure. In most programming languages you add elements to a stack using a push method, and take elements off the stack with pop, and Scala is no different.
Scala has both immutable and mutable versions of a stack. Stack extends from Seq.

Declaring Empty Stack
import scala.collection.mutable.Stack
var ints = Stack[Int]()
var fruits = Stack[String]()
case class Person(var name: String)
var people = Stack[Person]()
//stack with initial elements
val ints = Stack(1, 2, 3)

//Mutable stack, push elements onto the stack with push:
var fruits = Stack[String]()   //empty String Stack
fruits.push("apple")
fruits.push("banana")
fruits.push("coconut", "orange", "pineapple","apple")
//Output
fruits= Stack(apple, pineapple, orange, coconut, banana, apple)

//Take elements off the stack, pop them off:

//fruits stack contains (apple, pineapple, orange, coconut, banana, apple)
val next = fruits.pop
//Output : next: String = apple

//Peek next element of stack without removing it, using top:
//fruits contains (apple, pineapple, orange, coconut, banana, apple)
val sTop = fruits.top
//Output : sTop: String = apple

//Size of a Stack
fruits.size //6

//Check whether stack is empty or non-empty
fruits.isEmpty //false

//You can empty a mutable stack with clear
fruits.clear
fruits
fruits: scala.collection.mutable.Stack[String] = Stack()

No comments:

Post a Comment

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...