mapper
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
public class MavgaqiMapper extends Mapper<LongWritable, Text,Text,IntWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// 疏忽首行
// 用 key 判断,第一行的 key 肯定是 0
if (key.get()==0) {return;}
// 字符串类型转成 java 类型
String data = value.toString();
// 切片成数组,一共有 9 个元素
String[] msgs = data.split(",");
if (!(msgs[6].equals("N/A"))){context.write(new Text(msgs[0]),new IntWritable(Integer.parseInt(msgs[6])));
}
}
}
reducer
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
public class MavgaqiReducer extends Reducer<Text, IntWritable,Text, IntWritable> {
@Override
protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// 把解决的每一个 201601 的 value 值都加起来
int total = 0;
int count = 0;
int avg = 0;
for (IntWritable v:values){
// 把 IntWritable 类型转化为 int 型
count++;
total += v.get();}
avg = total/count;
//total 由 int 类型变为 FloatWritable 类型
context.write(key,new IntWritable(avg));
}
}
main
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
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;
public class MavgaqiMain {
public static void main(String[] args) throws Exception {Job job = Job.getInstance(new Configuration());
// 程序主类
job.setJarByClass(MavgaqiMain.class);
//Mapper 类的相干设置
job.setMapperClass(MavgaqiMapper.class);
//Map 输入 key,[PerfectMoney 下载](https://www.gendan5.com/wallet/PerfectMoney.html)value 类型
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);
//Reducer 类的相干设置
job.setReducerClass(MavgaqiReducer.class);
// 程序运行输入 key,value 类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// 设置输出,输入门路
FileInputFormat.setInputPaths(job,new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
// 提交工作,并期待工作运行实现
job.waitForCompletion(true);
}
}