spark 完成二次排序

先根据第一列的数字从大到小排序,如果相等,在按照第二列进行排序.
文件内容:
file3.txt

23 4
23 5
2 4
2 5
6 7
6 8
10 23
10 23
43 45
43 45
46 56
46 56

排序代码:
1、这个一个类:SecondarySortkey

/**
  * @author 
  * @date 2020-09-09 15:02
  * @version 1.0
  */
class SecondarySortkey(val first:Int,val second:Int) extends Ordered [SecondarySortkey] with Serializable {
   def compare(other: SecondarySortkey): Int = {
     if (this.first - other.first!=0) {
       this.first -other.first
     } else {
       this.second - other.second
     }
   }
}

2、这是一个对象

/**
  * @author navy
  * @date 2020-09-09 17:44
  * @version 1.0
  */
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
object SecondarySortApp {
  def main(args: Array[String]) = {
    val conf = new SparkConf().setAppName("SecondarySortApp!").setMaster("local")
    val sc = new SparkContext(conf)
    val lines=sc.textFile("/Users/navyliu/Downloads/spark/sparkcase/file3.txt",1)
    val pairWithSortKey = lines.map(line=>(new SecondarySortkey(line.split(" ")(0).toInt,line.split(" ")(1).toInt),line))
    val sorted = pairWithSortKey.sortByKey(false)
    val sortedResult = sorted.map(sortedLine=>sortedLine._2)
    sortedResult.collect().foreach(println)
  }
}

执行完之后,可以看到排序的结果
在这里插入图片描述
欲了解更多scala编程的内容,请关注公众号:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值