更新时间:2020年11月04日17时42分 来源:传智播客 浏览次数:
MapReduce程序会根据输入的文件产生多个map任务。Hadoop提供的Mapper类是实现Map任务的一个抽象基类,该基类提供了一个map()方法,默认情况下,Mapper类中的map()方法是没有做任何处理的。
如果我们想自定义map()方法,我们只需要继承Mapper类并重写map()方法即可。接下来,我们以词频统计为例,自定义一个map()方法,具体代码如文件所示。
文件 WordCountMapper.java
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;
public class WordCountMapper extends Mapper<LongWritable, Text,
Text, IntWritable> {
@Override
protected void map(LongWritable key, Text value, Mapper<
LongWritable, Text, Text, IntWritable>.Context context)
throws IOException, InterruptedException {
// 接收传入进来的一行文本,把数据类型转换为String类型
String line = value.toString();
// 将这行内容按照分隔符切割
String[] words = line.split(" ");
// 遍历数组,每出现一个单词就标记一个数组1 例如:<单词,1>
for (String word : words) {
// 使用context,把Map阶段处理的数据发送给Reduce阶段作为输入数据
**context.write(new Text(word), new IntWritable(1));**
}
}
}
猜你喜欢: