编写mapreduce程序,统计每个同学考试的总成绩
时间: 2024-05-01 18:22:41 浏览: 36
假设有一份包含学生姓名、科目和成绩的文件,格式如下:
```
Alice,Math,90
Bob,Math,80
Alice,English,85
Bob,English,95
Charlie,Math,75
Charlie,English,80
```
我们可以使用MapReduce来统计每个同学的总成绩。下面是一个简单的MapReduce程序:
```java
import java.io.IOException;
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;
public class ExamScore {
public static class ScoreMapper
extends Mapper<Object, Text, Text, IntWritable>{
private Text name = new Text();
private IntWritable score = new IntWritable();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
String[] fields = value.toString().split(",");
name.set(fields[0].trim()); // 学生姓名
score.set(Integer.parseInt(fields[2].trim())); // 成绩
context.write(name, score);
}
}
public static class ScoreReducer
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;
for (IntWritable val : values) {
sum += val.get(); // 累加成绩
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "exam score");
job.setJarByClass(ExamScore.class);
job.setMapperClass(ScoreMapper.class);
job.setCombinerClass(ScoreReducer.class); // 使用Combiner优化
job.setReducerClass(ScoreReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
在这个程序中,我们定义了两个类`ScoreMapper`和`ScoreReducer`,分别对应Map和Reduce任务。在Map任务中,我们将每个学生的姓名作为key,将其成绩作为value输出。在Reduce任务中,我们累加每个学生的成绩,并将其输出。我们还使用了一个Combiner来优化程序性能,将Map任务输出的中间结果进行合并。最后,在`main`函数中,我们指定了输入文件和输出文件的路径,并启动了MapReduce任务。
运行这个程序的命令如下:
```bash
hadoop jar ExamScore.jar ExamScore input output
```
其中,`ExamScore.jar`是打包好的程序包名,`input`是输入文件路径,`output`是输出文件路径。运行成功后,输出文件中将包含每个同学的姓名和总成绩。