package textSort
import org.apache.spark.{SparkConf, SparkContext}
object SortDemo02 extends App {
/*
* 自定义排序
* 排序规则给女明星排序 年龄 颜值 演技
*
* 注意 sortBy只应用于元组tuple
* */
val conf = new SparkConf().setAppName("SortDemo02").setMaster("local[2]")
val sc = new SparkContext(conf)
val starsRdd = sc.parallelize(List(Girl2("蔡明", 50, 80, 70), Girl2("高圆圆", 30, 90, 75), Girl2("冰冰", 30, 95, 80), Girl2("旺财", 32, 95, 80), Girl2("小花", 15, 95, 100)))
val arr1 = starsRdd.sortBy(t => t).collect() // 先颜值 演技 最后年龄小的排前面
println(arr1.toBuffer)
//结果(Girl(小花,15,95,100), Girl(冰冰,30,95,80), Girl(旺财,32,95,80), Girl(高圆圆,30,90,75), Girl(蔡明,50,80,70))
/*
* 封装在class中
* extends Ordered 相当于java中实现接口comparable 排序的功能
* Girl2类名不能重复!!!
*
* */
case class Girl2(name: String, age: Int, faceValue: Int, actValue: Int) extends Ordered[Girl2] with Serializable {
override def compare(that: Girl2): Int = {
if (this.faceValue == that.faceValue) { //如果颜值相等
that.actValue- this.actValue //就比较演技
} else if (this.actValue == that.actValue) {//如果演技相等
this.age- that.age //比较年龄 (年龄是小的在前 反序)
} else {
that.faceValue -this.faceValue //上面条件不成立就只需比较颜值了
}
}
}
}
spark之Sort(三)
最新推荐文章于 2024-01-05 09:41:07 发布