数据:
2012,01,01,5
2012,01,02,45
2012,01,03,35
2012,01,04,10
2012,02,04,10
2012,02,03,18
2012,02,01,22
2012,02,05,43
2001,11,01,46
2001,11,02,47
2001,11,03,48
2001,11,04,40
2005,08,20,50
2005,08,21,52
2005,08,22,38
2005,08,23,70
以上是一组温度数据,各个列分别为年、月、日和当天温度,
我们希望输出每一个“年-月”的温度,而且值按升序排列。
scala实现:
val config = new SparkConf().setMaster("local[2]").setAppName("c01")
val sc = new SparkContext(config)
sc.setLogLevel("WARN") val input = sc.textFile("C:\\Users\\john\\Desktop\\data\\dataAlgorithm\\chapter1\\c01.txt") val sorted = input.map(x => {
val line = x.split(",")
(line(0) + "-" + line(1), line(3).toInt)
}).groupByKey().sortByKey(true).map(x => (x._1,x._2.toList.sortWith(_<_))) sorted.foreach(x => println(x._1+": " + x._2.mkString(","))) 结果输出:
2001-11: 40,46,47,48
2012-01: 5,10,35,45
2005-08: 38,50,52,70
2012-02: 10,18,22,88