[英]Unable to add elements to scala mutable list inside foreach loop
我正在嘗試在mutable scala list
添加元素,如下所示。 我正在逐行讀取數據幀中的值,提取名稱為“_title”的列的值並將其添加到列表中。 但是當 for 循環完成時,列表仍然是空的。 這是代碼:
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)
實際上打印了我想放入列表中的值。 我的數據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 |
當我做
colListA += "elements"
colListA += "adds"
我可以看到添加的元素。 但不在那個foreach
循環中。 誰能告訴我我該嘗試什么? 基本上,我希望 colList 填充last_mod_date
和object_string
。
如果要從數據dataframe.select("_title").collect().map(_(0).asInstanceOf[String]).toList
列創建列表
您可以獲取列的字符串列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.