1

Suppose i am having mapping in following way :

[ (1,List[11,12,13]),(2,List[21,22,23]),(3,List[31,32,33]) ]

i want to convert/transform this in the form shown below :

[ (1,11),(1,12),(1,13),(2,21),(2,22),(2,23),(3,31),(3,32),(3,33)]

I am using scala 2.10.4

4 Answers 4

7

Use flatMap:

 val xs = Array( (1,List(11,12,13)),(2,List(21,22,23)),(3,List(31,32,33)) )
 xs.flatMap{ case (s, xs) => xs.map((s,_))}
Sign up to request clarification or add additional context in comments.

Comments

6

You can try:

array.flatMap { case (key, arr) => arr.map { key -> _ } }

Comments

3

A solution using for comprehension:

val input = List((1,List(11,12,13)),(2,List(21,22,23)),(3,List(31,32,33)))

val output = for {
  tuple <- input
  element <- tuple._2
} yield (tuple._1, element)

Comments

2

Maybe you would like this:

for {
   (k,arr) <- arrOfTuple
   el <- arr
 } yield (k -> el)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.