思路
首先按照月份來分組,對組內的數據按照溫度來排序
取溫度最高的前兩名,然后分組取RDD
代碼
public class TopNTemperature {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("TopNTemperature").setMaster("local[1]");
JavaSparkContext sc = new JavaSparkContext(conf);
JavaRDD<String> weatherRdd = sc.textFile("weather");
weatherRdd = weatherRdd.cache();
JavaPairRDD<String, List<Double>> top2TemperaturePerMonthRDD = weatherRdd.mapToPair(new PairFunction<String, String,Double>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<String, Double> call(String log) throws Exception {
String[] splited = log.split("\t");
String date = splited[0].substring(0, 7);
Double temperature = Double.parseDouble(splited[1].trim());
return new Tuple2<String, Double>(date,temperature);
}
})//生成(年月,溫度)的RDD
.groupByKey()//按照月份分組
.mapToPair(new PairFunction<Tuple2<String,Iterable<Double>>, String,List<Double>>() {
private static final long serialVersionUID = 1L;
@Override
public Tuple2<String, List<Double>> call(Tuple2<String, Iterable<Double>> tuple) throws Exception {
String date = tuple._1;
Iterator<Double> iterator = tuple._2.iterator();
Double[] temperatures = new Double[2];
//list
while(iterator.hasNext()){
//遍歷每一個月份
Double temperature = iterator.next();
for(int i = 0 ;i < temperatures.length ; i++){
//遍歷每一個月份里的溫度
if(temperatures[i] == null){
//判斷某一個月份里是否只有一個溫度,如果有不用排序了
temperatures[i] = temperature;
break;
}else{
if(temperature > temperatures[i]){
/**
* 有兩個以上的溫度,對Value值排序,取出最大的兩個數,類似于冒泡法
* temperature[]這個數組只能裝下兩個元素多于的就被淘汰了
*/
for(int j = (temperatures.length-1) ; j > i ;j--){
temperatures[j] = temperatures[j-1];
}
temperatures[i] = temperature;
break;
}
}
}
}
//Collections.sort()
List<Double> asList = Arrays.asList(temperatures);
return new Tuple2<String, List<Double>>(date,asList);
}
});
List<Tuple2<String, List<Double>>> collect = top2TemperaturePerMonthRDD.collect();
for(Tuple2<String,List<Double>> t:collect){
//collect算子:Action算子,能夠將每一個task的計算結果回收到Driver端,一般用于測試
String date = t._1;
List<Double> topN = t._2;
System.out.println("date:" + date + "\tTemperature:" + topN.get(0) + "\t" + topN.get(1));
}
sc.stop();
}
}
關于serialVersionUID
serialVersionUID適用于Java的序列化機制。簡單來說,Java的序列化機制是通過判斷類的serialVersionUID來驗證版本一致性的。在進行反序列化時,JVM會把傳來的字節流中的serialVersionUID與本地相應實體類的serialVersionUID進行比較,如果相同就認為是一致的,可以進行反序列化,否則就會出現序列化版本不一致的異常,即是InvalidCastException。