Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

MapReduce 經典案例:計算學生平均成績

本文以「計算學生各科平均成績」為例,分享一個完整的 MapReduce 實現。

資源文件 math
張三 99 李四 90 王五 90 趙六 60

資源文件 china
張三 79 李四 75 王五 80 趙六 90

資源文件 english
張三 89 李四 75 王五 70 趙六 90

分析:在 Map 階段,將學生姓名作為 key、成績作為 value 輸出。這樣 Reduce 階段拿到的數據就是 key:張三、value:{99,79,89}……在 Reduce 中對每位學生的成績求平均值即可。

實現:

package com.bwzy.Hadoop;
// ... 導入相關類
public class AvgSorce extends Configured implements Tool {
   public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
      public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
         String line = value.toString();
         StringTokenizer tokenizer = new StringTokenizer(line);
         while (tokenizer.hasMoreElements()) {
            String strName = tokenizer.nextToken();
            String strSorce = tokenizer.nextToken();
            context.write(new Text(strName), new IntWritable(Integer.parseInt(strSorce)));
         }
      }
   }
   public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {
      public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
         int sum = 0;
         int num = 0;
         for (IntWritable sorce : values) {
            sum += sorce.get();
            num++;
         }
         context.write(key, new IntWritable((int)(sum / num)));
      }
   }
   @Override
   public int run(String[] arg0) throws Exception {
      Job job = new Job(getConf());
      job.setJobName("AvgSorce");
      job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(IntWritable.class);
      job.setMapperClass(Map.class);
      job.setReducerClass(Reduce.class);
      job.setInputFormatClass(TextInputFormat.class);
      job.setOutputFormatClass(TextOutputFormat.class);
      FileInputFormat.setInputPaths(job, new Path(arg0[0]));
      FileOutputFormat.setOutputPath(job, new Path(arg0[1]));
      return job.waitForCompletion(true) ? 0 : 1;
   }
   public static void main(String[] args) throws Exception {
      System.exit(ToolRunner.run(new AvgSorce(), args));
   }
}

運行步驟:

  1. 將程序打包:選中打包的類 → 右擊 → Export → Java → JAR file → 填入保存路徑 → 完成。
  2. 將 jar 包拷貝到 Hadoop 目錄下(因為程序中用到了 Hadoop 的 jar 包)。
  3. 將資源文件上傳到 HDFS 目錄。創建目錄:hadoop fs -mkdir /自定義/自定義/input;上傳文件:hadoop fs -put /home/user/Document/math /自定義/自定義/input。
  4. 運行程序:hadoop jar AvgSorce.jar com.bwzy.hadoop.AvgSorce /自定義/自定義/input /自定義/自定義/output。Hadoop 會自動創建 output 目錄,其中一個文件存放運行結果。若重新運行,需先刪除 output 目錄,否則系統會認為結果已存在。

運行結果:

張三 89
李四 80
王五 80
趙六 80
Copyright © Linux教程網 All Rights Reserved