hadoop mapreduce求平均分
求平均分的关键在于,利用mapreduce过程中,一个key聚合在一起,输送到一个reduce的特性。
假设三门课的成绩如下:
china.txt
[plain]
张三 78
李四 89
王五 96
赵六 67
english.txt
[plain]
张三 80
李四 82
王五 84
赵六 86
math.txt
[plain]
张三 88
李四 99
王五 66
赵六 72
mapreduce如下:
[plain]
public static class map extends mapper {
// 实现map函数
public void map(longwritable key, text value, context context) throws ioexception, interruptedexception {
// 将输入的纯文本文件的数据转化成string
string line = value.tostring();
// 将输入的数据首先按行进行分割
stringtokenizer tokenizerarticle = new stringtokenizer(line, \n);
// 分别对每一行进行处理
while (tokenizerarticle.hasmoreelements()) {
// 每行按空格划分
stringtokenizer tokenizerline = new stringtokenizer(tokenizerarticle.nexttoken());
string strname = tokenizerline.nexttoken();// 学生姓名部分
string strscore = tokenizerline.nexttoken();// 成绩部分
text name = new text(strname);
int scoreint = integer.parseint(strscore);
// 输出姓名和成绩
context.write(name, new intwritable(scoreint));
}
}
}
public static class reduce extends reducer {
// 实现reduce函数
public void reduce(text key, iterable values, context context) throws ioexception, interruptedexception {
int sum = 0;
int count = 0;
iterator iterator = values.iterator();
while (iterator.hasnext()) {
sum += iterator.next().get();// 计算总分
count++;// 统计总的科目数
}
int average = (int) sum / count;// 计算平均成绩
context.write(key, new intwritable(average));
}
}
输出如下:
[plain]
张三 82
李四 90
王五 82
赵六 75
