基于Spark下自定义排序Demo

95 篇文章 0 订阅
29 篇文章 2 订阅
import org.apache.spark.{SparkConf, SparkContext}

object CustomSort {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setAppName("CustomSort").setMaster("local[2]")
    val sc = new SparkContext(conf)

    val rdd1 = sc.parallelize(List(("xiaoli",91,28,1),("xiaoming",89,25,6),("xiaohong",86,21,1)))
    import  OrderContext._
   /* def sortBy[K](
   f : scala.Function1[T, K], 
   ascending : scala.Boolean = { /* compiled code */ },
    numPartitions : scala.Int = { /* compiled code */ })
    (implicit ord : scala.Ordering[K], ctag : scala.reflect.ClassTag[K]) : org.apache.spark.rdd.RDD[T] = { /* compiled code */ }*/
    val rdd2 = rdd1.sortBy(x=>Gril(x._2,x._3),false)
    println(rdd2.collect().toBuffer)
    sc.stop()
  }
}
//case class Gril(openSize:Int,age:Int) extends Serializable
/*源码object Ordered {
  /** Lens from `Ordering[T]` to `Ordered[T]` */
  implicit def orderingToOrdered[T](x: T)(implicit ord: Ordering[T]): Ordered[T] =
    new Ordered[T] { def compare(that: T): Int = ord.compare(x, that) }
}*/
case class Gril(val openSize:Int,val age:Int) extends Ordered[Gril] with Serializable{
  override def compare(that: Gril): Int = {
    if (this.openSize == that.openSize){
      that.age - this.age
    }else{
      this.openSize - that.openSize
    }
  }
}

/**
  * 自定义排序
  */
object OrderContext{
  implicit  val grilOrdering = new Ordering[Gril]{
    override def compare(x: Gril, y: Gril): Int = {
      if (x.openSize > y.openSize){
        1
      }else if(x.openSize == y.openSize){
        if (x.age > y.age) -1 else 1
      }else -1
    }
  }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值