我正在尝试在 Scala 中 reduceByKeys,是否有任何方法可以根据 Scala 中的键来减少值。 [我知道我们可以通过 spark 中的 reduceByKey 方法来做,但是我们如何在 Scala 中做同样的事情? ]
输入数据是:
val File = Source.fromFile("C:/Users/svk12/git/data/retail_db/order_items/part-00000")
.getLines()
.toList
val map = File.map(x => x.split(","))
.map(x => (x(1),x(4)))
map.take(10).foreach(println)
在上述步骤之后,我得到的结果为:
(2,250.0)
(2,129.99)
(4,49.98)
(4,299.95)
(4,150.0)
(4,199.92)
(5,299.98)
(5,299.95)
预期结果 :
(2,379.99)
(5,499.93)
.......
最佳答案
看起来您想要文件中某些值的总和。一个问题是文件是字符串,所以你必须转换 String
在可以求和之前转换为数字格式。
这些是您可能会使用的步骤。
io.Source.fromFile("so.txt") //open file
.getLines() //read line-by-line
.map(_.split(",")) //each line is Array[String]
.toSeq //to something that can groupBy()
.groupBy(_(1)) //now is Map[String,Array[String]]
.mapValues(_.map(_(4).toInt).sum) //now is Map[String,Int]
.toSeq //un-Map it to (String,Int) tuples
.sorted //presentation order
.take(10) //sample
.foreach(println) //report
如果任何文件数据不是所需的格式,这当然会抛出。
关于scala - 如何在 "Scala"中按键减少 [Not In Spark],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54604432/