簡體   English   中英

無法將元素添加到 foreach 循環內的 Scala 可變列表

[英]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_dateobject_string

如果要從數據dataframe.select("_title").collect().map(_(0).asInstanceOf[String]).toList列創建列表

您可以獲取列的字符串列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM