mapreduce编程实现wordcount程序
时间: 2023-11-11 13:07:01 浏览: 227
下面是一个使用MapReduce实现WordCount程序的示例代码:
Mapper代码:
```java
public class WordCountMapper 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();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
word.set(tokenizer.nextToken());
context.write(word, one);
}
}
}
```
Reducer代码:
```java
public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
public void reduce(Text key, Iterable<IntWritable> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
context.write(key, new IntWritable(sum));
}
}
```
Main函数代码:
```java
public class WordCount {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(WordCountMapper.class);
job.setCombinerClass(WordCountReducer.class);
job.setReducerClass(WordCountReducer.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);
}
}
```
以上代码中,我们首先定义了一个Mapper类和一个Reducer类。Mapper类将输入的文本划分为单词,并将每个单词映射为(单词,1)的键值对;Reducer类对于每个单词的键值对进行合并,计算出每个单词出现的次数。
在Main函数中,我们创建了一个新的MapReduce任务,并指定了输入和输出路径。在任务的配置中,我们指定了Mapper类、Combiner类和Reducer类,并设置了键和值的类型。最后,我们调用waitForCompletion方法来等待任务完成。
阅读全文