To create a parallel collection from a sequential collection, call the par
method. To create a sequential collection from a parallel collection, call the seq
method. This example shows how you turn a regular Vector
into a ParVector
, and then back again:
scala> val vect = (1 to 5).toVector
vect: Vector[Int] = Vector(1, 2, 3, 4, 5)
scala> val parVect = vect.par
parVect: scala.collection.parallel.immutable.ParVector[Int] = ParVector(1, 2, 3, 4, 5)
scala> parVect.seq
res0: scala.collection.immutable.Vector[Int] = Vector(1, 2, 3, 4, 5)
The par
method can be chained, allowing you to convert a sequential collection to a parallel collection and immediately perform an action on it:
scala> vect.map(_ * 2)
res1: scala.collection.immutable.Vector[Int] = Vector(2, 4, 6, 8, 10)
scala> vect.par.map(_ * 2)
res2: scala.collection.parallel.immutable.ParVector[Int] = ParVector(2, 4, 6, 8, 10)
In these examples, the work is actually parceled out to multiple processing units, and then re-joined after the work is complete - without requiring developer intervention.