Spark二次排序、自定義排序

//spark進行二次排序 先按第一列排,相等情況下按第二列排

class SecondarySortKey(val first:Int,val second:Int) extends Ordered[SecondarySortKey] with Serializable{
  //必須重寫compare
  def compare(other:SecondarySortKey):Int ={
    if(this.first - other.first != 0){
      // 兩種情況>0 <0
      this.first - other.first
    } else{
      //三種情況 >0 =0 <0
      this.second - other.second
    }
  }
}
//spark進行自定義排序
//先按第一列String類型進行排序,相同情況下按第二列Int類型進行排序

class DefineSortKey(val first:String,val second:Int) extends Ordered[DefineSortKey] with Serializable{
  def compare(other:DefineSortKey):Int = {
    if(this.first != other.first){
      if(this.first > other.first) 1
      else -1
    } else{
      this.second - other.second
    }
  }
}

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章