#问题: 很多时候,我们需要对多个字段进行综合的排序,比如现在需要对英雄联盟中,莫个人分数最高的那局游戏信息。这个时候就需要将莫个人以及分数作为排序的字段。 也就需要定义一个case class(样例类)将这两个字段组装成为key,这个key extends Orderd[key] with Serialble接口。在这个key中重写他的compare方法,分别对这两个字段进行排序。
#代码实现: --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}
/**
* Created by liufu on 2016/11/18.
*/
object SortByMyself {
def main(args: Array[String]): Unit = {
val conf: SparkConf = new SparkConf().setAppName("SortByMyself").setMaster("local[2]")
val sc: SparkContext = new SparkContext(conf)
val rdd1: RDD[(String, Int, Int)] = sc.parallelize(List(("liufu",100,24),("jinagzhen",99,22),("liudehua",90,55),("baby",10,10)))
val rdd2: RDD[(String, Int, Int)] = rdd1.sortBy(msg => Gril(msg._2,msg._3))
println(rdd2.collect().toBuffer)
sc.stop()
}
}
//利用样例类来封装需要排序的字段, 类似于MapReduce中的自定义javabean来封装字段作为key。
//如果是this到that的顺序进行相减,是升序排序。
//如果想要降序排序,只需要把位置调一下既可以了。
//利用原生的compareto方法对每一个字段进行排序就可以了。很方便。
case class Gril(yanzhi:Int,nianling:Int) extends Ordered[Gril] with Serializable{
override def compare(that: Gril): Int = {
val yanzhiResult: Int = this.yanzhi.compareTo(that.yanzhi)
if(yanzhiResult == 0){
return this.nianling.compareTo(that.nianling)
}
return yanzhiResult
}
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------