原始數據
1949-10-01 14:21:02 34 23
1949-10-01 19:21:02 38 34
1949-10-02 14:01:02 36 56
1950-01-01 11:21:02 32 67
1950-10-01 12:21:02 37 11
1951-12-01 12:21:02 23 78
1950-10-02 12:21:02 41 39
1950-10-03 12:21:02 27 88
。。。。。
思路:
1.將數據讀取到RDD1中
2.將RDD1中的數據轉換成K-V格式的RDD2
3.對RDD2使用sortByKey排序
代碼
public class SecondSort {
public static void main(String[] args) {
//獲取溫度 濕度信息
SparkConf conf = new SparkConf().setAppName("SecondSort").setMaster("local[1]");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> weatherRdd = sc.textFile("weather");
/**
* mapToPair 算子是java api只能夠獨有的,在scala api中沒有這個算子 在scala中相當于map
* mapToPair可以返回一個KV格式的RDD
* 泛型解釋:
* String:wetherRDD中每一條元素的類型, SortObj:返回的RDD的key類型, String:返回的RDD的value類型
*/
weatherRdd.mapToPair(new PairFunction<String, SortObj, String>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<SortObj, String> call(String log) throws Exception {
//log = weatherRdd中每一條記錄
String[] splited = log.split("\t");
Integer temperature = Integer.parseInt(splited[1].trim());
Integer shidu = Integer.parseInt(splited[2]);
SortObj sortObj = new SortObj(temperature,shidu);
return new Tuple2<SortObj, String>(sortObj,log);
}
}).sortByKey()//對RDD2的溫度進行排序
.foreach(new VoidFunction<Tuple2<SortObj,String>>() {//遍歷RDD2中每一條數據
/**
* SortObj RDD2的key的類型 String RDD2的value類型
*/
private static final long serialVersionUID = 1L;
@Override
public void call(Tuple2<SortObj, String> t) throws Exception {
// TODO Auto-generated method stub
System.out.println(t);
}
/**
* SortObj RDD2 Key的類型
*/
});
sc.stop();
}
}
其中SortObj用來尋找溫度相同的元素
public class SortObj implements Serializable,Comparable<SortObj> {
private Integer temperature;
private Integer shidu;
public SortObj() {
super();
}
public SortObj(Integer temperature, Integer shidu) {
super();
this.temperature = temperature;
this.shidu = shidu;
}
public Integer getTemperature() {
return temperature;
}
public void setTemperature(Integer temperature) {
this.temperature = temperature;
}
public Integer getShidu() {
return shidu;
}
public void setShidu(Integer shidu) {
this.shidu = shidu;
}
@Override
public int compareTo(SortObj o) {
if(o.getTemperature() - getTemperature() == 0){
return o.getShidu() - getShidu();
}else{
return o.getTemperature() - getTemperature();
}
}
}
問題:
在scala中如何將一個非KV格式的RDD變成KV格式的RDD?
原則: 只要是xxToPair這樣的方法,他的返回值一定是一個KV格式的RDD