2

I have the following case classes

case class Outer(outerId: Integer, outerName: String, innerSeq:Seq[Inner]) case class Inner(innerName:String, innerAge: Integer, innerId: Integer) 

I created the following instances

val innerSeq1 = Seq(Inner("in10",10, 0),Inner("in11",11, 1), Inner("in12",12, 2)) val innerSeq2 = Seq(Inner("in20",10, 0),Inner("in21",11, 1), Inner("in22",12, 2)) val outerSeq = Seq(Outer(1, "out1", innerSeq1), Outer(2, "out2", innerSeq2 )) 

My intent is to create 3 element 3-tuples like this, I am not sure if I can use Zip or what to elegantly do this(I know a map then a map can do the iteration but I am not clear how will I get the below kind of output)

I want a 3-tuple in the following format (name of outer, name of inner, id of inner) Seq( (out1, in10, 0), (out1, in11, 1), (out1, in12, 2), (out2, in20, 0), (out2, in21, 1), (out2, in22, 2) ) Basically I want to while iterating over outersequence, want the triplets to be formed and get this flattened three tuplet output

5
  • So, you want one item for each outer, each one containing the triple of every inner, am I interpreting this correctly? Commented Jan 22, 2018 at 18:08
  • that is correct Commented Jan 22, 2018 at 18:17
  • curiousengineer, I wonder if there is something wrong with my updated answer. If there is - could you point out what works not as you wanted? Commented Jan 22, 2018 at 18:43
  • i just tick marked it :) Commented Jan 22, 2018 at 18:44
  • @curiousengineer, I've also added a for-comprehension-based way in case you prefer that. Commented Jan 22, 2018 at 18:55

1 Answer 1

2

Originally I misread your question. What you really want can be achieve with flatMap and inner map like this:

outerSeq.flatMap(o => o.innerSeq.map(i => (o.outerName, i.innerName, i.innerId))) 

If you prefer for-comprehension it might be even easier:

val res = for (o <- outerSeq; i <- o.innerSeq) yield (o.outerName, i.innerName, i.innerId) 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. Which is more functional :)? I remember, internally, one gets compiled into another though!
@curiousengineer, yes as the linked article says for-comprehension is compiled to exactly the same code. As to which is more functional, I think it is a question of taste. I think for-comprehension in this specific case produces a simpler code with a more clear intent. However others are entitled to different opinion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.