Maximum Length for scala queue

Viewed 7765

I'm curious if Scala has some gem hidden in its collection classes that I can use. Basically I'm looking for something like a FIFO queue, but that has an upper-limit on its size such that when the limit is hit, the oldest (first) element is removed from the queue. I've implemented this myself in Java in the past, but I'd rather use something standard if possible.

4 Answers

This is the approach I toke with extending Scala's standard mutable.Queue class.

class LimitedQueue[A](maxSize: Int) extends mutable.Queue[A] {
  override def +=(elem: A): this.type = {
    if (length >= maxSize) dequeue()
    appendElem(elem);
    this
  }
}

And simple use-case

var q2 = new LimitedQueue[Int](2)
q2 += 1
q2 += 2
q2 += 3
q2 += 4
q2 += 5

q2.foreach { n =>
  println(n)
}

You'll get only 4 and 5 in the console as the old elements were dequeued beforehand.

Related