spark 二次排序实现
2016-06-04 15:27
369 查看
一、文本格式([b]sort.txt)[/b]
1 5
2 4
3 6
1 3
2 1
二、编写类
package com.scala
/**
* scala处理二次排序的类
* 需要有参数
*/
class SecondSortByK(val first:Int,val second :Int) extends Ordered[SecondSortByK] with Serializable{
def compare(other:SecondSortByK):Int={
//this关键字可加,也可不加,如果遇到多个变量时,必须添加
if(this.first-other.first!=0)
this.first-other.first
else
this.second-other.second
}
//重写toString方法
override def toString():String={
"first:"+first+" second:"+second
}
}
三、编写排序类
package com.scala
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
/**
* scala版本的二次排序
*/
object SecondSortt {
def main(args:Array[String]):Unit={
val conf=new SparkConf().setAppName("SortSecond").setMaster("local[1]")
//获取context
val sc=new SparkContext(conf)
//加载到内存RDD
val lines=sc.textFile("sort.txt")
//map操作
val pairs=lines.map { x =>{
val spl=x.split(" ")
(new SecondSortByK(spl(0).toInt,spl(1).toInt),x)
} }
//sortByKey
val results=pairs.sortBy(x=>x._1, true)
//遍历
results.foreach(x=>{
println("result is "+x._1)
})
sc.stop()
}
}
1 5
2 4
3 6
1 3
2 1
二、编写类
package com.scala
/**
* scala处理二次排序的类
* 需要有参数
*/
class SecondSortByK(val first:Int,val second :Int) extends Ordered[SecondSortByK] with Serializable{
def compare(other:SecondSortByK):Int={
//this关键字可加,也可不加,如果遇到多个变量时,必须添加
if(this.first-other.first!=0)
this.first-other.first
else
this.second-other.second
}
//重写toString方法
override def toString():String={
"first:"+first+" second:"+second
}
}
三、编写排序类
package com.scala
import org.apache.spark.SparkConf
import org.apache.spark.SparkContext
/**
* scala版本的二次排序
*/
object SecondSortt {
def main(args:Array[String]):Unit={
val conf=new SparkConf().setAppName("SortSecond").setMaster("local[1]")
//获取context
val sc=new SparkContext(conf)
//加载到内存RDD
val lines=sc.textFile("sort.txt")
//map操作
val pairs=lines.map { x =>{
val spl=x.split(" ")
(new SecondSortByK(spl(0).toInt,spl(1).toInt),x)
} }
//sortByKey
val results=pairs.sortBy(x=>x._1, true)
//遍历
results.foreach(x=>{
println("result is "+x._1)
})
sc.stop()
}
}
相关文章推荐
- 体育竞技游戏的团队AI
- orr r0,r0,#R1_nF:OR:R1_iA
- 二十分钟学会Javascript初级语法
- XTU Binary Search Tree(LIS变形)
- NFC读取卡号学习
- 浅谈Java中的System.gc()的工作原理
- C# 一些常用的技巧代码
- 机器学习:EM算法_续
- spark模拟密集型计算任务
- List的4种迭代方法
- ARM linux kernel启动流程
- 机器学习-KMeans聚类 K值以及初始类簇中心点的选取
- ASP.NET MVC 下UpdateModel可空未填写的参数为Null,为何不是空字符串
- Dom-docment-通过节点层次关系获取
- 2016.06.04 教学妹弄gephi遇到的一些问题
- javascript获取select标签选中的值
- Linux配置vim ctags g++ IDE GDB
- java通过JDBC链接SQLServer2012
- struct msghdr
- 10秒后显示图片