hadoop统计以a和b字母开头的单词的个数代码
时间: 2023-11-12 16:09:09 浏览: 175
hadoop简单单词统计
下面是一个简单的Hadoop MapReduce代码,用于统计以a和b字母开头的单词的个数:
Mapper类:
```
public class ABWordCountMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
String nextToken = tokenizer.nextToken();
if (nextToken.startsWith("a") || nextToken.startsWith("b")) {
word.set(nextToken);
context.write(word, one);
}
}
}
}
```
Reducer类:
```
public class ABWordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
@Override
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类:
```
public class ABWordCountDriver {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "AB word count");
job.setJarByClass(ABWordCountDriver.class);
job.setMapperClass(ABWordCountMapper.class);
job.setCombinerClass(ABWordCountReducer.class);
job.setReducerClass(ABWordCountReducer.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);
}
}
```
在运行MapReduce作业之前,请确保已经安装并配置好了Hadoop,并且已经将输入文件上传到HDFS中。使用以下命令来提交MapReduce作业:
```
hadoop jar ABWordCount.jar ABWordCountDriver input output
```
其中,ABWordCount.jar是包含所有类文件的JAR文件,input是输入文件的路径,output是输出文件的路径。
阅读全文