Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Seq or List to collection.immutable.Queue

I wonder, if there is a standard and short way to convert Sequence to immutable Queue in Scala?

I did not find a magic method in documentation.

Right now I'm doing it like this:

def toQueue[A](s: Seq[A]): Queue[A] = s match {
  case x +: xs => x +: toQueue(xs)
  case _ => Queue.empty[A]
}                                         

But is there anything more convenient?

like image 332
Viacheslav Rodionov Avatar asked Mar 20 '14 11:03

Viacheslav Rodionov


3 Answers

Starting Scala 2.13, via factory builders applied with .to(factory):

List(1, 2, 3).to(collection.immutable.Queue)
// collection.immutable.Queue[Int] = Queue(1, 2, 3)

Prior to Scala 2.13 and starting Scala 2.10:

List(1, 2, 3).to[collection.immutable.Queue]
// collection.immutable.Queue[Int] = Queue(1, 2, 3)
like image 138
Xavier Guihot Avatar answered Oct 27 '22 09:10

Xavier Guihot


Why not use s: _*?

val s = List(1, 2, 3) // or Seq(1, 2, 3), as you wish
val queue = scala.collection.immutable.Queue(s: _*)
like image 23
serejja Avatar answered Oct 27 '22 07:10

serejja


var s=new scala.collection.mutable.Queue[Any];
var li:List[Any]=List(1,'a',"bing",4,7,9,'j');
for(i<-0 to li.length-1)
{
    s.+=(li(i))
}
like image 22
Guru Avatar answered Oct 27 '22 09:10

Guru