MapReduce程式設計(四) 求均值

weixin_34117211發表於2017-03-31

一、問題描述

三個檔案中分別儲存了學生的語文、數學和英語成績,輸出每個學生的平均分。

資料格式如下:
Chinese.txt

張三    78
李四    89
王五    96
趙六    67

Math.txt

張三    88
李四    99
王五    66
趙六    77

English.txt

張三    80
李四    82
王五    84
趙六    86

二、MapReduce程式設計

package com.javacore.hadoop;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;


/**
 * Created by bee on 3/29/17.
 */
public class StudentAvgDouble {

    public static class MyMapper extends Mapper<Object, Text, Text, DoubleWritable> {

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
           String eachline = value.toString();
           StringTokenizer tokenizer = new StringTokenizer(eachline, "\n");
            while (tokenizer.hasMoreElements()) {
                StringTokenizer tokenizerLine = new StringTokenizer(tokenizer
                        .nextToken());
                String strName = tokenizerLine.nextToken();
                String strScore = tokenizerLine.nextToken();
                Text name = new Text(strName);
                IntWritable score = new IntWritable(Integer.parseInt(strScore));
                context.write(name, score);
            }
        }
    }

    public static class MyReducer extends Reducer<Text, DoubleWritable, Text, DoubleWritable> {
        public void reduce(Text key, Iterable<DoubleWritable> values, Context
                context) throws IOException, InterruptedException {
            double sum = 0.0;
            int count = 0;
            for (DoubleWritable val : values) {
                sum += val.get();
                count++;
            }
            DoubleWritable avgScore = new DoubleWritable(sum / count);
            context.write(key, avgScore);
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {

        //刪除output資料夾
        FileUtil.deleteDir("output");
        Configuration conf = new Configuration();
        String[] otherArgs = new String[]{"input/studentAvg", "output"};
        if (otherArgs.length != 2) {
            System.out.println("引數錯誤");
            System.exit(2);
        }

        Job job = Job.getInstance();
        job.setJarByClass(StudentAvgDouble.class);
        job.setMapperClass(MyMapper.class);
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);
        FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
}

三、StringTokenizer和Split的用法對比

map函式裡按行讀入,每行按空格切開,之前我採用的split()函式切分,程式碼如下。

 String eachline = value.toString();
 for (String eachline : lines) {
                System.out.println("eachline:\t"+eachline);
                String[] words = eachline.split("\\s+");
                Text name = new Text(words[0]);
                IntWritable score = new IntWritable(Integer.parseInt(words[1]));
                context.write(name, score);
            }

這種方式簡單明瞭,但是也存在缺陷,對於非正常編碼的空格有時候會出現切割失敗的情況。
StringTokenizer是java.util包中分割解析類,StringTokenizer類的建構函式有三個:

  1. StringTokenizer(String str):java預設的分隔符是“空格”、“製表符(‘\t’)”、“換行符(‘\n’)”、“回車符(‘\r’)。
  2. StringTokenizer(String str,String delim):可以構造一個用來解析str的StringTokenizer物件,並提供一個指定的分隔符。
  3. StringTokenizer(String str,String delim,boolean returnDelims):構造一個用來解析str的StringTokenizer物件,並提供一個指定的分隔符,同時,指定是否返回分隔符。

    StringTokenizer和Split都可以對字串進行切分,StringTokenizer的效能更高一些,分隔符如果用到一些特殊字元,StringTokenizer的處理結果更好。

四、執行結果

張三  82.0
李四  90.0
王五  82.0
趙六  76.66666666666667

相關文章