1

我有以下代码:

 val lines =  Source.fromFile("/home/cloudera/file_01").getLines().drop(1).toVector

我得到一个文件行向量 - 这是文件:

lines: Vector[String] = Vector(blk1|20170912|||||, ||||||, |c1|c2|c3|||, |201710|201711|201712|||, v1|1|4|9|||, v2|1||7|||, blk2||||||, ||||||, c4|c5|c6||||, |201710|201711|201712|||, h|h|h|h|h|h|h, j|j|j|j|j|j|j, k|k|k|k|k|k|k, m|m|m|m|m|m|m, ||||||, ||||||, ||||||, 201801|1|5||||, 201802|9|100||||, 201803|9|||||)

然后我想要做的是获取每个字符串数组的条目,然后放入字符串数组数组中。

我明白了,这很好:

scala> val current_line_values_1 = lines(3).split("\\|", -1).map{x => val trimmed = x.trim; if (trimmed.isEmpty) "empty string" else trimmed}
current_line_values_1: Array[String] = Array(empty string, 201710, 201711, 201712, empty string, empty string, empty string)

scala> val current_line_values_2 = lines(3).split("\\|", -1).map{x => val trimmed = x.trim; if (trimmed.isEmpty) "empty string" else trimmed}
current_line_values_2: Array[String] = Array(empty string, 201710, 201711, 201712, empty string, empty string, empty string)

这样做是为了在 SBT 控制台中简单。

所以,我查看了 ListBuffer,因为我想制作这 2 个列表,它们是所有行的子集。

我按照 mutable.ListBuffer 使用 Alvin Alexander 的示例进行了以下操作:

var fruits = new ListBuffer[String]()
//var fruits = new ListBuffer[Array[String]]()  - this made no difference either

fruits += current_line_values_1.toString
fruits += current_line_values_2.toString

我不得不使用 toString 来编译它。

我得到了正确数量的元素,但是像这样打印出来:

      saveLinesList1 = fruits.toList

      // How to print 2 dimensional?
      for (j <- 0 to (saveLinesList1.length - 1)) {

        println("hello " + saveLinesList1(j))
        val x = saveLinesList1(j)
           for (k <- 0 to (x.length - 1)) {
             println("hello 2 " + x(k))
           }

      } // End of for loop.

给我:

hello [Ljava.lang.String;@51dd09f
hello 2 [
hello 2 L
hello 2 j
hello 2 a
hello 2 v
hello 2 a

内容发生了什么变化?Array [String] 的数组也没有帮助。查看二维数组也没有清除它。

我所需要的只是一个字符串数组的行数组。

4

1 回答 1

2

当您申请toString时,Array它将返回对象而不是String值。而是尝试使用mkStringwhich 连接 Array 中的每个值并返回单个String值。尝试使用下面的代码,

//no need to define it as var its already mutable
val fruits = new ListBuffer[String]()
fruits += current_line_values_1.mkString
fruits += current_line_values_2.mkString
//to print the ListBuffer
fruits.foreach(println(_))

如果你需要Array[String]而不是String你可以使用以下,

val fruits = new ListBuffer[Array[String]]()
fruits += current_line_values_1
fruits += current_line_values_2
于 2018-01-24T11:36:16.330 回答