求平均数以及数据清洗
package hadoop;
//每个人平均花多少钱
//并且对数据进行清洗
/**
- 数据样式:姓名,日期,金额,三个字段
- 数据:
- 张三,20198-1,30
- 张三,20198-2,30
- 李四,20198-1,30
- 李四,20198-2, —日期位置是空格 --在空格位置填0,不会影响数据
- 李四,20198-3,, —日期位置是逗号
- 李四,20198-4, , —日期位置是空格
- 王五,20198-1
- 王五,20198-1,30
*/
package hadoop;
//每个人平均花多少钱
//并且对数据进行清洗
/**
- 数据样式:姓名,日期,金额,三个字段
- 数据:
- 张三,20198-1,30
- 张三,20198-2,30
- 李四,20198-1,30
- 李四,20198-2, —日期位置是空格 --在空格位置填0,不会影响数据
- 李四,20198-3,, —日期位置是逗号
- 李四,20198-4, , —日期位置是空格
- 王五,20198-1
- 王五,20198-1,30
*/
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
public class MapReduce_avgClean {
public static class MyMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws java.io.IOException ,InterruptedException
{
//数据样式:姓名,日期,金额,三个字段
String line = value.toString();
String[] split = line.split(",");
//对数据进行过滤,将数组长度不为3的过滤出去
//首先将字段不满足数量的过滤掉
if(split.length == 3) {
//将关键字段不满足需求的进行清洗,回填
if(split[2].equals(null) || split[2].equals("") || split[2].equals(" ")) {
split[2] = "0";
}
String name = split[0];
Long money = Long.parseLong(split[2]);
context.write(new Text(name), new LongWritable(money));
}
};
}
public static class MyReduce extends Reducer<Text, LongWritable, Text, LongWritable>{
@Override
protected void reduce(Text k2, Iterable<LongWritable> v2s,
Reducer<Text, LongWritable, Text, LongWritable>.Context context) throws IOException, InterruptedException {
//在reduce算出消费总和,以及消费次数,因为在同一个reduce中是同一个人消费
//所以直接算出reduce的数据条数
long sum = 0l;
//定义次数
long count = 0l;
for (LongWritable value : v2s) {
count++;
sum += value.get();
}
context.write(k2, new LongWritable(sum/count));
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, MapReduce_sumClean.class.getSimpleName());
job.setJarByClass(MapReduce_avgClean.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
job.setMapperClass(MyMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setReducerClass(MyReduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
}
}