Hadoop案例求平均成绩

 
//思路根据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(),"\n");
   
   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);
}
}

转载于:https://my.oschina.net/u/1169079/blog/201960

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值