Home > database >  Scala: how to flatten an Array of a tuple of tuples?
Scala: how to flatten an Array of a tuple of tuples?

Time:10-21

I'm trying to flatten the following structure at scala:

Array[((String, String, String),(String, String, String))]

To obtain:

(String, String, String, String, String, String)

So far, I tried something similar to:

val  = payload.map(_.productIterator.toList.map(_.toString)).toList

which produces: List[List[String]]

Any ideas about how to achieve this?

Thanks!

CodePudding user response:

Tuples aren't something which can be easily flattened - Scala 3 offers the way to concatenate them:

val xs: Array[((String, String, String),(String, String, String))]

xs.map { case (t1, t2) =>
  t1    t2
} // Array[(String, String, String, String, String, String)]

but in Scala 2 you'd have to combine them manually

val xs: Array[((String, String, String),(String, String, String))]

xs.map { case ((a, b, c), (d, e, f)) =>
  (a, b, c, d, e, f)
} // Array[(String, String, String, String, String, String)]

Once you have array of tuples... you still cannot "just" flatten it because what would be intuitive, build-in, default way of combining all tuples in array into one tuple? You can do it, e.g. with foldLeft/foldRight/reduce but you still have to tell HOW:

val xs2: Array[(String, String, String, String, String, String)]

xs2.foldLeft(initialValue) { (tuple1, tuple) =>
  // your definition how to combine them
}

e.g. if you wanted to concatenate values on corresponding positions

val xs: Array[((String, String, String),(String, String, String))]

xs.map { case ((a, b, c), (d, e, f)) =>
  (a, b, c, d, e, f)
}.foldLeft(("", "", "", "", "", "")) {
  case ((a1,b1,c1,d1,e1,f1), (a2,b2,c2,d2,e2,f2)) =>
    (a1 a2, b1 b2, c1 c2, d1 d2, e1 e2, f1 f2)
} // (String, String, String, String, String, String)

It could also be done in 1 step with:

val xs: Array[((String, String, String),(String, String, String))]

xs.foldLeft(("", "", "", "", "", "")) {
  case ((a1,b1,c1,d1,e1,f1), ((a2,b2,c2),(d2,e2,f2))) =>
    (a1 a2, b1 b2, c1 c2, d1 d2, e1 e2, f1 f2)
} // (String, String, String, String, String, String)

But the exact implementation depends on what you understand by "flattening" array of tuples of tuples into a tuple.

CodePudding user response:

to flatten - you need to call flatten

val x=Seq(("A","B","C"),("D","E","F"),("H","I","J"))
x.map(_.productIterator.toSeq).flatten

or use a flatMap

val x=Seq(("A","B","C"),("D","E","F"),("H","I","J"))
x.flatMap(_.productIterator.toSeq)
  • Related