TAGS :Viewed: 11 - Published at: a few seconds ago

[ Scala tuple of collections instead of collection of tuples ]

In one invocation to map we construct a collection of tuples, for instance like this,

val a = (1 to 5).map { x => (x, x*10) }
a: Vector((1,10), (2,20), (3,30), (4,40), (5,50))

and then we extract the first and second elements into two separate, immutable collections

val b1 = a.map {_._1}
b1: Vector(1, 2, 3, 4, 5)

val b2 = a.map {_._2}
b2: Vector(10, 20, 30, 40, 50)

How to obtain b1 and b2 by iterating over the initial collection once only,

val (b1,b2) = (1 to 5).map { x => /* ??? */ }

Answer 1


Use unzip:

scala> (1 to 5).unzip { x => x -> x * 3 }
res0: (Vector(1, 2, 3, 4, 5),Vector(3, 6, 9, 12, 15))

Answer 2


Note that IonuČ› G. Stan's answer is the same as:

(1 to 5).unzip{ x => (x, x * 3)}

which makes how to get triples of collections back even clearer:

(1 to 5).unzip3{ x => (x, x * 3, x * 10)}