【Hadoop】WordCount案例详解

本文详细介绍了一个经典的WordCount案例实现过程,包括如何通过MapReduce框架处理大量文本数据,并统计每个单词出现的频次。该案例使用了Hadoop平台,具体介绍了Mapper和Reducer两个核心阶段的工作原理及其实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

WordCount案例详解


需求:文件中存储的各种各样的单词,统计在这些文件中每个单词的出现次数

WordCount Map阶段

原理:针对每行数据应用map方法,按照分隔符拆分;Map阶段输出单词作为key,1作为value。

WordCount Reduce阶段

原理:从Map阶段拷贝对应的输出结果,统计每个单词出现的总词数

代码

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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;

import java.io.FileOutputStream;
import java.io.IOException;

public class WC_MR {
    static class WCMapper extends Mapper<LongWritable,Text,Text,LongWritable>{
        @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){
                context.write(new Text(word),new LongWritable(1));
            }
        }
    }

    static class WCReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            int count = 0;
            for(LongWritable value : values){
                count += value.get();
            }
            context.write(key,new LongWritable(count));

        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        String input = args[0];
        String output = args[1];

        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf);
        job.setJobName("wordcount");
        
        job.setJarByClass(WC_MR.class);
        
        job.setMapperClass(WCMapper.class);
        job.setReducerClass(WCReducer.class);
        
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);
        
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        FileInputFormat.setInputPaths(job,new Path(input));
        FileOutputFormat.setOutputPath(job,new Path(output));

        System.exit(job.waitForCompletion(true)?0:1);
    }
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

镰刀韭菜

看在我不断努力的份上,支持我吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值