【问题标题】:List not updating inside "foreach" statement, returning empty list列表未在“foreach”语句中更新,返回空列表
【发布时间】:2019-07-26 02:32:54
【问题描述】:

我想创建一个数据框并使用 foreach 遍历每一行,然后使用 foreach 行,创建一个名为 newSample 的对象,该对象由 3 个字符串组成,并将此 newSample 附加到名为 SampleList 的列表中。最后,我会得到一个newSample的列表,并使用sparktoDF语句将列表转换成一个新的dataframe。

由于 List 是不可变的,我也尝试使用 ListBuffer 代替 List

case class newSample(userID: String, featureName: String, featureValue: String)
var sampleList = List[newSample]()
// userFeatures is a list of strings, which are column names of df_short dataframe
// userID is a string, which is also the name a column of df_short    
   for (features <- userFeatures){
      val dfTemp = df_short.select(userID, features)
      dfTemp.foreach( Row =>{
        sampleList = newSample(Row.get(0).toString, features, Row.get(1).toString) :: sampleList
      })
      println(sampleList)
    }
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()
List()

每次打印出来的sampleList 不应该是空的。但它是一个空列表。

【问题讨论】:

    标签: scala dataframe apache-spark foreach


    【解决方案1】:

    List 有一个花哨的flatMap 函数,可以让您将列表中的每个元素扩展为多个,最后将它们全部收集到一个列表中。这样您就不需要使用任何可变的东西,无论是 ListBuffer 还是 foreach 方法。

        case class NewSample(userID: String, featureName: String, featureValue: String)
        val newSampleList = userFeatures.flatMap { feature =>
            df_short
              .select(userID, feature)
              .map(Row => NewSample(Row.get(0).toString, feature, Row.get(1).toString) :: sampleList)
              .collect()
              .toList
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多