curiousengineer
curiousengineer

Reputation: 2607

Nested sequence iteration in scala, zip

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

Upvotes: 2

Views: 835

Answers (1)

SergGr
SergGr

Reputation: 23788

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)

Upvotes: 2

Related Questions