一、实现功能
获取Top10 word单词
二、实现方法
1.方法1.sortBy
val textFile = sc.textFile("file:///opt/modules/spark-2.1.0-bin-2.7.3/README.md")
val wordRDD=textFile.flatMap(_.split(" ")).map((_,1)).reduceByKey(_ + _)
wordRDD.sortBy(t => t._2 * -1).take(10)
2.方法2:sortByKey
val textFile = sc.textFile("file:///opt/modules/spark-2.1.0-bin-2.7.3/README.md")
val wordRDD=textFile.flatMap(_.split(" ")).map((_,1)).reduceByKey(_ + _)
wordRDD.map(t => (t._2 * -1, t)).sortByKey().map(t => t._2).take(10)
注意:t._2 * -1一定要有空格!在shell中t._2*-1是错误的!
3.方法3.top
将String,int的二元组进行排序,先比较第一个,再比较第二个。但是如果只想比较数字,就要把数字放到前面,所以通过swap转换位置。
(1)wordRDD.map(_.swap).top(10).map(_.swap)
或者
(2)wordRDD.top(10)(ord = new scala.math.Ordering[(String,Int)]{
override def compare(x: (String,Int), y: (String,Int)): Int = {
x._2.compare(y._2)
}
})