Monday, 6 May 2019

Queue in Scala


Queue
Queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and mutable queue. This recipe demonstrates the mutable queue.
You can create an empty, mutable queue of any data type:
import scala.collection.mutable.Queue
var ints = Queue[Int]()
var fruits = Queue[String]()
var q = Queue[Person]()
You can also create a queue with initial elements :
val q = Queue(1, 2, 3)

 Add elements with +=, ++=, enqueue :

Once you have a mutable queue, add elements to it using +=, ++=, and enqueue, as shown in the following examples:

import scala.collection.mutable.Queue
var q = Queue[String]()
q += "apple"
println(q)
//Queue(apple)
q += ("kiwi", "banana")
println(q)
//Queue(apple, kiwi, banana)
q ++= List("cherry", "coconut")
println(q)
//Queue(apple, kiwi, banana, cherry, coconut)
q.enqueue("pineapple")
println(q)

//Queue(apple, kiwi, banana, cherry, coconut, pineapple)

Dequeue
Because a queue is a FIFO, you typically remove elements from the head of the queue, one element at a time, using dequeue:
var q = Queue(“apple”, “kiwi”, “banana”, “cherry”, “coconut”, “pineapple”)
q.dequeueprintln(q)
//Queue(kiwi, banana, cherry, coconut, pineapple)

DequeueFirst, DequeueAll

You can also use the dequeueFirst and dequeueAll methods to remove elements from the queue by specifying a predicate
var q = Queue(“apple”, “kiwi”, “banana”, “cherry”, “coconut”, “pineapple”)
q.dequeueFirst(_.startsWith("b"))
println(q)
// Queue(apple, kiwi, cherry, coconut, pineapple)
//Queue(apple, kiwi, banana, cherry, coconut, pineapple)
q.dequeueAll(_.length > 6)
println(q)

//Queue(apple, kiwi, banana, cherry)

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...