本文主要是介绍MapReduce(eclipse)求2020年部门工资平均值,求2021年员工平均工资,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
注意点:
1.部门工资表需要为.csv格式,如下:
我们可以通过wps新建xls,xlsx的Excel表格,做好的表格另存为csv格式
还需注意另存为csv格式时你的Excel只能有一个工作表,如下:
我的.csv表格如下:
我只是完成作业所以年份下的月份只写了一月和二月的大家可以按自己需求增加!
部门号即为上图中的A那一行,写入Mapper端即为words[0].
2.以下是我的代码
(1)Mapper端代码
package MapReduce;import java.io.IOException;import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
// k1 v1 k2(年份) v2工资
public class WordCountMapper extends Mapper<LongWritable,Text,IntWritable, IntWritable >{protected void map(LongWritable key1, Text value1, Context context) throws IOException, InterruptedException {String line = value1.toString();// 数据:部门 员工姓名 年份 月份 工资String[] words = line.split(",");//,分割//输出k2, v2//2021年【12】工资【14】+【16】//2020年 部门号【0】 工资【4】+【6】context.write(new IntWritable(Integer.parseInt(words[12])), new IntWritable(Integer.parseInt(words[14])+Integer.parseInt(words[16])));}}
(2):Reducer端代码
package MapReduce;import java.io.IOException;import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;// k3 v3 k4 v4
public class WordCountReducer extends Reducer<IntWritable,IntWritable,IntWritable,IntWritable> {protected void reduce(IntWritable k3, Iterable<IntWritable>v3,Context context)throws IOException, InterruptedException {//对工资求和int total = 0;//求平均int deptNumber = 0;for(IntWritable v:v3) {total +=v.get();deptNumber++;}//输出:年份 工资总数平均值context.write(k3, new IntWritable(total/deptNumber));//按月统计部门的平均工资//context.write(k3, new IntWritable(total/12));}}
(3):Drive端代码
package MapReduce;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;public class WordCountDrive {public static void main(String[] args) throws Exception {//创建一个job和任务入口(指定主类)Job job = Job.getInstance(new Configuration());//指定job的mapper和输出的类型<k2 v2>job.setMapperClass(WordCountMapper.class);job.setMapOutputKeyClass(IntWritable.class);job.setMapOutputValueClass(IntWritable.class);//指定job的reducer和输出的类型<k4 v4>job.setReducerClass(WordCountReducer.class);job.setOutputKeyClass(IntWritable.class);job.setOutputValueClass(IntWritable.class);//指定job的输入和输出路径FileInputFormat.setInputPaths(job, new Path("D:\\年份月份工资表.csv"));FileOutputFormat.setOutputPath(job, new Path("D:\\a4"));//执行jobboolean result = job.waitForCompletion(true);if (result) {System.out.println("完成!");}else {System.out.println("失败!");}}
}
求2021年的平均工资(我只求了2021年一月和二月的)的平均工资运行结果如下:
这篇关于MapReduce(eclipse)求2020年部门工资平均值,求2021年员工平均工资的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!