scala 实现自定义排序算法

来源:互联网 发布:冠趣网络 编辑:程序博客网 时间:2024/06/05 00:57
scala 实现自定义排序算法--数据aaa.txt:4 13 28 72 34 32 1package com.lhj.wwwclass KeyPair(val first:Int,val second:Int) extends Ordered[KeyPair] with Serializable{   def compare(other: KeyPair): Int = {    if(this.first-other.first != 0){      this.first-other.first    }else{      this.second-other.second    }  }}package com.lhj.wwwimport org.apache.spark.{SparkContext, SparkConf}object Test {  def main(args: Array[String]) {    val conf = new SparkConf().setAppName("my app!!!").setMaster("local")    val sc = new SparkContext(conf)    val sorted = sc.textFile("aaa.txt").map(x=>(new KeyPair(x.split(" ")(0).toInt,x.split(" ")(1).toInt),x)).sortByKey(false)//    (com.lhj.www.KeyPair@63c41670,8 7)//    (com.lhj.www.KeyPair@5e9d463b,4 3)//    (com.lhj.www.KeyPair@276dfc04,4 1)//    (com.lhj.www.KeyPair@25bc7ed5,3 2)//    (com.lhj.www.KeyPair@7a2ae54d,2 3)//    (com.lhj.www.KeyPair@163460e4,2 1)    val result=sorted.map(x=>(x._2))    result.collect().foreach(println)  }}--结果:8 74 34 13 22 32 1

0 0
原创粉丝点击