hadoop MapReduce工资统计代码
时间: 2023-07-09 21:47:16 浏览: 92
以下是一个使用Hadoop MapReduce框架来统计工资数据的简单示例代码:
Mapper部分:
```java
public class SalaryMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split(",");
int salary = Integer.parseInt(fields[2]);
// 将薪资范围映射为对应的key
if (salary < 10000) {
word.set("<10000");
} else if (salary < 20000) {
word.set("10000-20000");
} else if (salary < 30000) {
word.set("20000-30000");
} else {
word.set(">30000");
}
context.write(word, one);
}
}
```
Reducer部分:
```java
public class SalaryReducer 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);
}
}
```
Driver部分:
```java
public class SalaryCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Salary Count");
job.setJarByClass(SalaryCount.class);
job.setMapperClass(SalaryMapper.class);
job.setCombinerClass(SalaryReducer.class);
job.setReducerClass(SalaryReducer.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);
}
}
```
以上代码用于统计薪资范围在<10000, 10000-20000, 20000-30000, >30000之间的员工数量。输入文件为CSV格式的员工信息文件,每行为一个员工的id、姓名和薪资。输出文件为每个薪资范围对应的员工数量。
阅读全文