我有以下代码:
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] 的数组也没有帮助。查看二维数组也没有清除它。
我所需要的只是一个字符串数组的行数组。