Reputation: 3459
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
}
}
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.
Upvotes: 0
Views: 123
Reputation: 27421
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)
Upvotes: 5