云计算分布式框架 Hadoop

107课时
2.2K学过
8分

课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
5分钟

实现Map类

这个类实现Mapper接口中的Map方法,输入参数中的value是文本文件中的一行,利用tringTokenizer将这个字符串拆成单词,然后将输出结果<单词,1>写到org.apache. hadoop.mapred.OutputCollector 中。OutputCollector由Hadoop框架提供,负责收集Mapper和 Reducer输出的数据,实现Map函数和Reduce函数时,只需简单地将其输出的<key,value>对传送给OutputCollector即可,剩余的任务由框架处理。

代码中LongWritable、IntWritable、Text 均是Hadoop中实现的用于封装Java数据类型的类,这些类都能够被串行化从而便于在分布式环境中进行数据交换,可以将它们分别视为long、int、String的替代品。Reporter可用于报告整个应用的运行进度,本例中未使用。

//定义map方法继承Mapper接口
public static class Map extends MapReduceBase implements Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();
    /*实现 Mapper 接口中的 map方法,输入参数中的 value 是文本文件中的一行,
利用 StringTokenizer将这个字符串拆成单词
*/
    public void map(LongWritable key, Text value, OutputCollector<Text, IntWritable> output, 
    Reporter reporter) throws IOException {
        String line = value.toString();
        StringTokenizer tokenizer = new StringTokenizer(line);
        while (tokenizer.hasMoreTokens()) {
            word.set(tokenizer.nextToken());
            //输出结果<单词,1>
            output.collect(word, one);
        }  
    }
}