How to arrange scala parallel collections in insertion order?

Rah*_*Raj 0 scala vector scala-collections

Consider the below example:

object Test {
def main(args: Array[String]): Unit = {
  val vec = Vector(1,2,3,4,5,6)
  val x = vec.map(myFunc(_))
  x.foreach{println}

  val par = vec.par
  val parx = par.map(myFunc(_))
  parx.foreach{println}
}

def myFunc(a:Int) : Int  = {
 return a*a
 }
}
Run Code Online (Sandbox Code Playgroud)

when I print x, it follows insertion order, while parx follows random order. How to preserve the insertion order here? I'm using Vector in this example, but it happens in other collections such as List too.

Tim*_*Tim 5

parx is a parallel collection so all operations on it are done in parallel, including foreach. So all the println operations are executed in parallel, and you cannot control the order in which they complete.

If you want to go back to a sequential collection, call .seq on the collection.

parx.seq.foreach(println)
Run Code Online (Sandbox Code Playgroud)