参考原文:
http://www.cnblogs.com/little-YTMM/p/4396008.html
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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 WordCount {
public static class TokenizerMapper
/*
* Mapper的前两个参数为输入K1,V1。后两个参数为输出K2,V2.
* 本例中K1为文章ID且不重要,V1为文章内容,因此是Text类型。K2为输出的单词因此也为Text类型,V2为计数,因此为IntWritable。
* 由于key和value在程序运行时需要被Hadoop框架序列化,因此必须实现Writable接口。
* 另外key必须实现WritableComparable,这样框架才能对其进行排序。
*/
extends Mapper<Object, Text, Text, IntWritable>{
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
/*
* LongWritable 为输入的key的类型
* Text 为输入value的类型
* Text-IntWritable 为输出key-value键值对的类型
*/
public void map(Object key, Text value, Context context //这里前两个参数对应K1,V1。即输入键值对。
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString()); // 将TextInputFormat生成的键值对转换成字符串类型
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one); //这里word和one对应输出的K2,V2
}
}
}
public static class IntSumReducer
/*
* 和Mapper一样,Reducer的前两个参数为输入K1,V1。后两个参数为输出K2,V2.
*/
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable();
/*
* Text-IntWritable 来自map的输入key-value键值对的类型
* Text-IntWritable 输出key-value 单词-词频键值对
*/
public void reduce(Text key, Iterable<IntWritable> values, //这里前两个参数对应K1,V1。即输入键值对。
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration(); // job的配置
Job job = Job.getInstance(conf, "word count"); // 初始化Job
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.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);
}
}