A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change.
In Scala, Queue is implemented as a pair of lists. One is used to insert the elements and second to contain deleted elements. Elements are added to the first list and removed from the second list. The two most basic operations of Queue are Enqueue and Dequeue.
- Enqueue – Adding an element at the end of the queue.
- Dequeue – Deleting an element from the beginning of the queue.
Methods in Queue:
- +=: This method is used to add a single element in the end of the queue.
- ++=: This method is used to Insert more than one the element in the end of the queue.
- clear: Remove all elements from the queue.
- dequeue: Returns the first element in the queue
- enqueue: Adds all the elements to the queue.
- equals: Checks if two queues are structurally identical.
- front: Returns the first element in the queue.
- isEmpty: Check if the queue is empty or not.
Below are simple Scala programs to demonstrate these operations:
Queue Elements: 1 2 3 4 5 First element in the queue: 1 Queue Elements after enqueue: 1 2 3 4 5 10 Queue Elements after dequeue: 2 3 4 5 10 Dequeued element: 1 Queue is empty: false
Queue Elements: apple banana mango guava First element in the queue: apple Queue Elements after enqueue: apple banana mango guava pineapple Queue Elements after dequeue: banana mango guava pineapple Dequeued element: apple clear the queue: () queue is empty:true
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.