我正在嘗試學習 Scala。我尋求幫助以了解回圈foreach 我有一個函式,它只讀取路徑中的最后一個 csv。但是當我只指出一種方式時它會起作用:
val path = "src/main/resources/historical_novel/"
def getLastFile(path: String, spark: SparkSession): String = {
val hdfs = ...}
但我怎樣才能將此功能應用于串列,例如
val paths: List[String] = List(
"src/main/resources/historical_novel/",
"src/main/resources/detective/",
"src/main/resources/adventure/",
"src/main/resources/horror/")
我想得到這樣的結果:
src/main/resources/historical_novel/20221027.csv
src/main/resources/detective/20221026.csv
src/main/resources/adventure/20221026.csv
src/main/resources/horror/20221027.csv
我用列(路徑)創建 df ,然后通過 WithColumn 應用函式,它是作業,但我想用foreach來做,理解它。
uj5u.com熱心網友回復:
假設你的功能是這樣的
def f(s: String): Unit = {}
你可以簡單地做到這一點
paths.foreach(p => f(p))
在您編輯之后,我想您可能想要使用map一個可以將一個集合轉換為另一個集合的函式。像這樣
val result = paths.map(p => getLastFile(p, yourSparkSession))
uj5u.com熱心網友回復:
foreach對 a 中的每個元素應用您定義或提供的函式Collection。
最簡單的例子是將每條路徑列印到控制臺
paths.foreach(path => println(path))
要應用您描述的一系列函式,您可以{}在foreach正文中使用并呼叫多個函式。
paths.foreach(path => {
val file = loadFile(path)
writeToDataBase(file)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/524179.html
標籤:斯卡拉阿帕奇火花前锋
