如何在scala中将任意数据类型的数组转换成逗号分隔的字符串

vuktfyat  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(849)

我现在的代码是:

schema.fields.foreach(f => {
                              if (f.dataType.typeName == "array") {
                                throw ArrayDataTypeNotSupportedException(s"${f.name} column is ArrayType, " +
                                  "writing arrays to CSV isn't supported. Please convert this column to a different data type.")
                              }
                            })

目前我们不支持csv中的数组,但现在希望通过将数组转换为字符串来支持任何数据类型的数组。字符串应以逗号分隔。
测试用例:

test("testArrayInSchema") {
    val df = spark.createDataFrame(Seq(
      TestDataSetArrays(
        Array(1, 2, 3),
        Array("a", "b", "c"),
        Array(new Timestamp(0), new Timestamp(1), new Timestamp(3))
      )
    ))
    assertThrows[ArrayDataTypeNotSupportedException] {
            writeDataFrame(df)

    }

现在我们需要删除这个异常,因为我们需要通过将数组转换为字符串来支持数组

whitzsjs

whitzsjs1#

要将数组转换为逗号分隔的字符串,可以使用mkstring(“,”)方法,例如:

val arr = Array("test1", "test2")
 arr.mkString(", ")

相关问题