1、有words.txt文件内容如下,其中以制表符分割
1 xiaoming 18
2 xiaohong 17
3 xiaoli
4 xiaowang 20
2、分析
map阶段
(1)、mapreduce逐行读取文件,得到每行的值
(2)、首先判断该行不是空字符串
(3)、满足以制表符分割后,长度必须大于3
(4)、将整行当做key输出
reduce阶段
(1)、map阶段将相同的key聚合在一起,但value为空
(2)、直接输出key即可
3、创建maven工程后,添加如下依赖
<dependencies>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-hdfs</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-mapreduce-client-core</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
4、编写mapreduce程序
package com.qujiuge.handle_lackval;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
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;
import java.io.IOException;
public class Driver {
static class LackMapper extends Mapper<LongWritable, Text, Text, NullWritable> {
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split("\t");
if (fields.length == 3) {
context.write(value, NullWritable.get());
}
}
}
static class LackReducer extends Reducer<Text, NullWritable, Text, NullWritable> {
@Override
protected void reduce(Text key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
context.write(key, values.iterator().next());
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Configuration config = new Configuration();
Job job = Job.getInstance(config);
job.setJarByClass(Driver.class);
job.setMapperClass(LackMapper.class);
job.setReducerClass(LackReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(NullWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
FileSystem fs = FileSystem.get(config);
Path outPath = new Path(args[1]);
if (fs.exists(outPath)) {
fs.delete(outPath, true);
}
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, outPath);
boolean result = job.waitForCompletion(true);
System.exit(result ? 0 : 1);
}
}
项目结构如下:
5、将words.txt文件上传到hdfs中
6、将项目打包成jar文件后,用hadoop jar命令执行
运行结果: