1

I have the following tuples: (1,"3idiots",List("Action","Adventure","Horror") Which I need to convert into a list in the following format:

List(
  (1,"3idiots","Action"),
  (1,"3idiots","Adventure")
)
3
  • 2
    please add the code ? Commented Jan 27, 2017 at 9:08
  • 2
    So what have you tried? Where are you stuck? What functions do you think would be useful? You have read the documentation, right? (Hint: flatMap) Commented Jan 27, 2017 at 9:12
  • 2
    and what about "Horror"? Commented Jan 27, 2017 at 9:40

4 Answers 4

6

To add to previous answers, you can also use for-comprehension in this case; it might make things clearer IMHO:

for(
     (a,b,l) <- ts; 
     s <- l
) yield (a,b,s)

So if you have:

val ts = List(
  ("a","1", List("foo","bar","baz")),
  ("b","2", List("foo1","bar1","baz1"))
)

You will get:

List(
      (a,1,foo), 
      (a,1,bar), 
      (a,1,baz),
      (b,2,foo1), 
      (b,2,bar1), 
      (b,2,baz1)
 )
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming that you have more than one tuple like this:

val tuples = List(
    (1, "3idiots", List("Action", "Adventure", "Horror")),
    (2, "foobar", List("Foo", "Bar"))
)

and you want result like this:

List(
    (1, "3idiots", "Action"),
    (1, "3idiots" , "Adventure"),
    (1, "3idiots", "Horror"),
    (2, "foobar", "Foo"),
    (2, "foobar", "Bar")
)

the solution for you would be to use a flatMap, which can convert a list of lists to a single list:

tuples.flatMap(t =>
    t._3.map(s =>
        (t._1, t._2, s)
    )
)

or shorter: tuples.flatMap(t => t._3.map((t._1, t._2, _)))

Comments

1

This should do what you want:

val input = (1,"3idiots",List("Action","Adventure","Horror"))    
val result = input._3.map(x => (input._1,input._2,x))
// gives List((1,3idiots,Action), (1,3idiots,Adventure), (1,3idiots,Horror))

Comments

1

You can use this.

val question = (1,"3idiots",List("Action","Adventure","Horror"))
val result = question._3.map(x=> (question._1 , question._2 ,x))

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.