RangesConcrete Immutable Collection ClassesImmutable stacksImmutable QueuesContents

Immutable Queues

A Queue is just like a stack except that it is first-in-first-out rather than last-in-first-out.

Here's how you can create an empty immutable queue:

scala> val empty = scala.collection.immutable.Queue[Int]()
empty: scala.collection.immutable.Queue[Int] = Queue()

You can append an element to an immutable queue with enqueue:

scala> val has1 = empty.enqueue(1)
has1: scala.collection.immutable.Queue[Int] = Queue(1)

To append multiple elements to a queue, call enqueue with a collection as its argument:

scala> val has123 = has1.enqueue(List(23))
has123: scala.collection.immutable.Queue[Int]
  = Queue(1, 2, 3)

To remove an element from the head of the queue, you use dequeue:

scala> val (element, has23) = has123.dequeue
element: Int = 1
has23: scala.collection.immutable.Queue[Int] = Queue(2, 3)

Note that dequeue returns a pair consisting of the element removed and the rest of the queue.

Next: Ranges


RangesConcrete Immutable Collection ClassesImmutable stacksImmutable QueuesContents