简体   繁体   English

无法将元素添加到 foreach 循环内的 Scala 可变列表

[英]Unable to add elements to scala mutable list inside foreach loop

I am trying to add elements in a mutable scala list as below.我正在尝试在mutable scala list添加元素,如下所示。 I am reading the values from a dataframe row by row, extracting out values of column with name "_title" and adding it to list.我正在逐行读取数据帧中的值,提取名称为“_title”的列的值并将其添加到列表中。 But when for loop is complete, the list is still enmpty.但是当 for 循环完成时,列表仍然是空的。 this is the code:这是代码:

import scala.collection.mutable.ListBuffer
val flatK = dfR.withColumn("UserValue", explode(col("UserValue")))
var colListA = new ListBuffer[String]()
//    var colSet : List[String] = List()
    for(i <- 0 until Integer.parseInt(dfR.count().toString)){
      flatK.filter($"columnIndex" === i).foreach{
        r=>
          val columnName = r.getAs[Row]("UserValue").getAs[String]("_title")
//          println(columnName)
          colListA.append(columnName)
      }
    }

println(columnName) actually prints the value I want to put inside my list. println(columnName)实际上打印了我想放入列表中的值。 My dataframe dfR looks like this:我的数据dfR如下所示:

 +--------------------------------------------------------------+-----------+
|UserValue                                                     |columnIndex|
+--------------------------------------------------------------+-----------+
|[, last_mod_date, 2009-01-14T13:40:53]                        |0          |
|[, object_string, SOLIDS]                                     |0          |
|[, last_mod_date, 2009-01-13T22:58:30]                        |1          |
|[, object_string, TORSO]                                      |1          |

When I do当我做

colListA += "elements"
colListA += "adds"

I can see elements added.我可以看到添加的元素。 But not inside that foreach loop.但不在那个foreach循环中。 Can any one tell me what shall I try?谁能告诉我我该尝试什么? Basically, I expect colList to be populated with last_mod_date and object_string .基本上,我希望 colList 填充last_mod_dateobject_string

If you want to create a list from column of a dataframe dataframe.select("_title").collect().map(_(0).asInstanceOf[String]).toList如果要从数据dataframe.select("_title").collect().map(_(0).asInstanceOf[String]).toList列创建列表

you can get the list of string of your column.您可以获取列的字符串列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM