11.27. Using a Queue
Problem
You want to use a queue data structure in a Scala application.
Solution
A 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:
scala> val q = Queue(1, 2, 3)
q: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3)
Once you have a mutable queue, add elements to it using +=
, ++=
,
and enqueue
, as shown in the
following examples:
scala>import scala.collection.mutable.Queue
import scala.collection.mutable.Queue // create an empty queue scala>var q = new Queue[String]
q: scala.collection.mutable.Queue[String] = Queue() // add elements to the queue in the usual ways scala>var q = new Queue[String]
q: scala.collection.mutable.Queue[String] = Queue() scala>q += "apple"
res0: scala.collection.mutable.Queue[String] = Queue(apple) scala>q += ("kiwi", "banana")
res1: scala.collection.mutable.Queue[String] = Queue(apple, kiwi, banana) scala>q ++= List("cherry", "coconut")
res2: scala.collection.mutable.Queue[String] = Queue(apple, kiwi, banana, cherry, coconut) // can also use enqueue scala>q.enqueue("pineapple")
scala>q
res3: scala.collection.mutable.Queue[String] = Queue(apple, kiwi, banana, cherry, coconut, pineapple)
Because a queue is a FIFO, you ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.