Scala Collections - Stack



Stack is Last In First Out, LIFO data structure and allows to insert and retrieve element at top, in LIFO manner.

Declaring Stack Variables

The following is the syntax for declaring an Stack variable.

Syntax

val stack = Stack(1, 2, 3, 4, 5)

Here, stack is declared as an Stack of numbers. Value can be added at top by using commands like the following −

Command

stack.push(6)

Value can be retrived from top by using commands like the following −

Command

stack.top

Value can be removed from top by using commands like the following −

Command

stack.pop

Processing Stack

Below is an example program of showing how to create, initialize and process Stack −

Example

import scala.collection.mutable.Stack
object Demo {
   def main(args: Array[String]) = {
      var stack: Stack[Int] = Stack();
      // Add elements
      stack.push(1);
      stack.push(2);
      // Print element at top
      println("Top Element: " + stack.top)
      // Print element
      println("Removed Element: " + stack.pop())
      // Print element
      println("Top Element: " + stack.top)	
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Top Element: 2
Removed Element: 2
Top Element: 1

Checking if the Stack is Empty

To check if the Stack is empty, you can use the isEmpty method. This method returns true if the Stack is empty, otherwise false. This is useful for ensuring that the Stack has elements before performing operations that assume it is not empty.

Syntax

val isEmpty = stack.isEmpty

Example

import scala.collection.mutable.Stack

object Demo {
  def main(args: Array[String]): Unit = {
    val stack = Stack[Int]()
    println(s"Is stack empty? ${stack.isEmpty}") 
    // Push 1 into empty stack
    stack.push(1)
    println(s"Is stack empty? ${stack.isEmpty}") 
  }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Is stack empty? true
Is stack empty? false

Iterating through a Stack

You can iterate through the elements of a Stack using a foreach loop. This allows you to perform an action on each element in the Stack, which can be useful for tasks like printing elements or applying a function to each one.

Example

import scala.collection.mutable.Stack

object Demo {
  def main(args: Array[String]): Unit = {
    val stack = Stack(1, 2, 3, 4, 5)
    // Iterating through stack using foreach
    stack.foreach(element => println(element))
  }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

1
2
3
4
5

Transforming Stacks

You can transform a Stack by applying a transformation function to each element using the map method. This method returns a new Stack with the transformed elements, allowing for operations like scaling, formatting, or any other transformation.

Example

Try following example for transforming stack elements -

import scala.collection.mutable.Stack

object Demo {
  def main(args: Array[String]): Unit = {
    val stack = Stack(1, 2, 3, 4, 5)
    // Doubling elements of stack using map function
    val doubledStack = stack.map(_ * 2)
    println(doubledStack) 
  }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Stack(2, 4, 6, 8, 10)

Filtering Stacks

You can filter elements in a Stack based on a predicate function using the filter method. This method returns a new Stack containing only the elements that satisfy the predicate, which is useful for extracting subsets of the data.

Example

import scala.collection.mutable.Stack

object Demo {
  def main(args: Array[String]): Unit = {
    val stack = Stack(1, 2, 3, 4, 5)
    // Filter even numbers of stack using filter function
    val evenStack = stack.filter(_ % 2 == 0)
    println(evenStack) 
  }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Stack(2, 4)

Converting a Stack to Other Collections

You can convert a Stack to other collections such as lists, arrays, or sequences. This is useful when you need to use the Stack data in a different context where a different type of collection is required.

Example

Try following example for converting a stack into other collections -

import scala.collection.mutable.Stack

object Demo {
  def main(args: Array[String]): Unit = {
    val stack = Stack(1, 2, 3, 4, 5)
    // Convert stack into list
    val list = stack.toList
    // Convert stack into array
    val array = stack.toArray
    // Convert stack into sequence
    val seq = stack.toSeq
    println(list) 
    println(array.mkString(", ")) 
    println(seq) 
  }
}

Save the above program in Demo.scala. Use the following commands to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(1, 2, 3, 4, 5)
1, 2, 3, 4, 5
Stack(1, 2, 3, 4, 5)

Scala Stack Summary

  • Stacks are mutable collections that follow the LIFO principle.
  • You can perform basic operations such as pushing, popping, and checking the top element on a Stack.
  • Stacks can be iterated, transformed, filtered, and converted to other collections.
  • Scala provides the Stack class in the collection.mutable package for creating and manipulating stacks.
Advertisements