Scala:如何展平元组的数组?

6ss1mwsb  于 2022-11-09  发布在  Scala
关注(0)|答案(2)|浏览(169)

我正试图在Scala中扁平化以下结构:

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

要获得以下信息:

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

到目前为止,我尝试了类似的方法:

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

生产:List[List[String]]
对如何实现这一点有什么想法吗?
谢谢!

m3eecexj

m3eecexj1#

元组不是很容易扁平化的东西--Scala3提供了连接它们的方法:

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

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

但在Scala2中,您必须手动组合它们

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)]

一旦你有了元组的数组...您仍然不能“只是”展平它,因为将数组中的所有元组组合成一个元组的直观、内置、默认的方法是什么?你可以这样做,例如,用foldLeft/foldRight/Reduce,但你仍然需要知道怎么做:

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

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

例如,如果您想串联相应位置上的值

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)

它还可以通过以下一步完成:

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)

但确切的实现取决于您对将元组的元组数组“扁平”为元组的理解。

t30tvxxf

t30tvxxf2#

您可以使用ProductIterator,但由于它返回需要与您拥有的类型匹配的任何内容:

val x=Seq((("A","B","C"),("D","E","F")),(("A1","B1","C1"),("D1","E1","F1")))
x.flatMap(_.productIterator
    .flatMap{
        case ys:(String, String, String)=>
          ys.productIterator.map{ 
               case xs:String => xs 
  }})

res0: Seq[String] = List(A, B, C, D, E, F, A1, B1, C1, D1, E1, F1)

相关问题