【问题标题】:Scala ListBuffer data not accessibleScala ListBuffer 数据不可访问
【发布时间】:2018-01-24 11:20:53
【问题描述】:

我有以下代码:

 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] 的数组也没有帮助。看二维数组也不清楚。

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

【问题讨论】:

    标签: scala listbuffer


    【解决方案1】:

    当您将toString 应用于Array 时,它将返回对象而不是String 值。而是尝试使用 mkString 连接 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
    

    【讨论】:

    • 唯一的问题是我失去了存在字段/元素的事实
    • 无法再访问这些,我想我错过了什么
    • 需要 Array[String],但认为它有帮助
    • @thebluephantom 编辑了 Array[String] 的答案。
    • 事实上它帮助了我。
    猜你喜欢
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2011-09-28
    • 1970-01-01
    相关资源
    最近更新 更多