Will the foreach
method of a Scala immutable Queue always be processed in the order one expects for a queue or is there a method that guarantees the order? Or do I have to use a loop + dequeue
?
scala.collection.immutable.Queue
is scala.collection.Seq
. See Seq
documentation:
Sequences are special cases of iterable collections of class Iterable. Unlike iterables, sequences always have a defined order of elements.
So yes, you'll get the same elements order with foreach
and with loop + dequeue
.
If you don't trust documentation you could take a look at implementation:
Queue#foreach
is inherited from IterableLike
and implemented like this:
def foreach[U](f: A => U): Unit = iterator.foreach(f)
Queue#iterator
is implemented like this:
override def iterator: Iterator[A] = (out ::: in.reverse).iterator
And Queue#dequeue
returns the first element of out
, if any, or the last element of in
. So you'll get the same elements order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With