Hadoopケース平均成績を求める

2067 ワード

 
// hadoop , key, value , , 。
public class AverageScore {
public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{
 
 private Text word = new Text();
   
 public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
   // 
  StringTokenizer line = new StringTokenizer(value.toString(),"
");        while (line.hasMoreElements()) {       //       StringTokenizer lineBlock = new StringTokenizer(line.nextToken());    String stuName = lineBlock.nextToken();    int stuScore = Integer.parseInt(lineBlock.nextToken());            word.set(stuName);          context.write(word, new IntWritable(stuScore));    }  } }
public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
 private IntWritable result = new IntWritable();
 public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
   int sum = 0;
   int count =0;
   while(values.iterator().hasNext()){
    sum+=values.iterator().next().get();
    count++;
   }
   int average = sum/count;
   result.set(average);
   context.write(key, result);
 }
}
public static void main(String[] args) throws Exception {
 Configuration conf = new Configuration();
 String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
 if (otherArgs.length != 2) {
   System.err.println("Usage: wordcount <in> <out>");
   System.exit(2);
 }
 Job job = new Job(conf, "word count");
 job.setJarByClass(AverageScore.class);
 job.setMapperClass(TokenizerMapper.class);
 job.setCombinerClass(IntSumReducer.class);
 job.setReducerClass(IntSumReducer.class);
 job.setOutputKeyClass(Text.class);
 job.setOutputValueClass(IntWritable.class);
 FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
 FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
 System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}