MapReduce怎么求每个学生平均数啊 我算出来结果只有是把成绩重新打出来了

img

我只发了核心的代码reduce阶段,你可以借鉴下,不懂我可以解释


```java
public class AvgReducer extends Reducer<Text, Avg,Text, DoubleWritable> {
    int sum=0;

    @Override
    protected void reduce(Text key, Iterable<Avg> values, Context context) throws IOException, InterruptedException {

        String sub="";
        for (Avg avg:
            values ) {
            if(sub.equals("")){
                sub=avg.getKe();
            }
           sum+=avg.getScore();
            }
            double s=sum/key.getLength();
        context.write(key,new DoubleWritable(s));
        }
}

```


 
package com.hpu.hadoop.test;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class MyMapper extends Mapper<LongWritable, Text,Text, DoubleWritable> {
    private Text K;
    private DoubleWritable V;
    @Override
    protected void setup(Context context) throws IOException, InterruptedException {
        K = new Text();
        V = new DoubleWritable();
    }
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] split = value.toString().split("\t");
        K.set(split[0]);
        double sum = Double.parseDouble(split[1]) + Double.parseDouble(split[2]) + Double.parseDouble(split[3]);
        V.set(sum/3);
        context.write(K,V);
    }
}
 

package com.hpu.hadoop.test;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.io.IOException;
 
public class MyDriver {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJarByClass(MyDriver.class);
        job.setMapperClass(MyMapper.class);
        job.setNumReduceTasks(0);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DoubleWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);
        //指定输入、输出路径
        FileInputFormat.setInputPaths(job,new Path(""));
        FileOutputFormat.setOutputPath(job,new Path(""));
        boolean b = job.waitForCompletion(true);
        System.exit(b?0:1);
    }
}
 

可以尝试下我这个方案,只要mapper就够了