案例:WorkCount
<key,value>
key:文件中的行的偏移量
value:行中的数据
- Mapper
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
/**
* LongWritable 偏移量 long,表示该行在文件中的位置,而不是行号
* Text map阶段的输入数据 一行文本信息 字符串类型 String
* Text map阶段的数据字符串类型 String
* IntWritable map阶段输出的value类型,对应java中的int型,表示行号
*/
public class WorkCountMap extends Mapper<LongWritable, Text, Text, IntWritable>{
/**
* key 输入的 键
* value 输入的 值
* context 上下文对象
*/
@Override
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String[] words = line.split("/t");//分词
for(String word : words) {
Text wordText = new Text(word);
IntWritable outValue = new IntWritable();
//写出
context.write(wordText, outValue);
}
}
}
- Reduce
reduce阶段的输入 是 mapper阶段的输出
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
/**
* Text 数据类型:字符串类型 String
* IntWritable reduce阶段的输入类型 int
* Text reduce阶段的输出数据类型 String类型
* IntWritable 输出词频个数 Int型
*/
public class WorkCountReduce extends Reducer<Text, IntWritable, Text, IntWritable>{
/**
* key 输入的 键
* value 输入的 值
* context 上下文对象,用于输出键值对
*/
@Override
protected void reduce(Text key, Iterable<IntWritable> value,
Context context) throws IOException, InterruptedException {
int sum=0;
for (IntWritable number : value) {
sum += number.get();
}
//单词 个数 hadoop,10
context.write(key, new IntWritable(sum));
}
}