MapReduce实例----统计平均成绩

本文介绍了一个使用Hadoop实现的学生分数平均计算程序。通过Mapper和Reducer处理学生分数数据,最终输出每位学生的平均成绩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.源数据:

张三 90
李四 100
张三 60
李四 80
王五 88
李四 100

2.代码如下:

package com.average;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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 org.apache.hadoop.util.GenericOptionsParser;


public class Average {
	public static class Map extends Mapper<Object, Text, Text, IntWritable>{
		
		public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
			String line=value.toString();
			String[] line1=line.split(" ");
			String person=line1[0].toString();
			IntWritable i=new IntWritable(Integer.parseInt(line1[1]));
			//System.out.print(person+" "+i);
			context.write(new Text(person), i);
		}
	}
	
	public static  class Redudce extends Reducer<Text, IntWritable, Text, IntWritable>{
		private static IntWritable i=new IntWritable(1);
		public  void reduce(Text key,Iterable<IntWritable> value,Context context) throws IOException, InterruptedException{
			
			int sum=0; //总分
			int ave=0;
			int count=0; //个数
			for(IntWritable v:value){
				sum+=v.get();
				count++;
				//System.out.println(v);
			}
			ave=sum/count;
			IntWritable ave1=new IntWritable(ave);
		
			context.write(key, ave1);
			System.out.println(key+"  "+ave1);
		}
	}
	public static void main(String args[]) throws IOException, ClassNotFoundException, InterruptedException{
		Configuration conf=new Configuration();
		String otherargs[]=new GenericOptionsParser(conf, args).getRemainingArgs();
		if(otherargs.length!=2){
			System.exit(2);
		}
		Job job=new Job(conf,"average");
		job.setJarByClass(Average.class);
		job.setMapperClass(Map.class);
		job.setCombinerClass(Redudce.class);
		job.setReducerClass(Redudce.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);

	     }



}

程序运行后输出文件夹里面是空的,也是很苦恼。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

w_t_y_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值