hadoop-mapreduce-2

WordCount需求: 在一堆给定的文本文件中统计输出每一个单词出现的总次数Step 1. 数据格式准备创建一个新的文件cd /export/serversvim wordcount.txt向其中放入以下内容并保存hello,world,hadoophive,sqoop,flume,hellokitty,tom,jerry,worldhadoop上传到 HDFShdfs dfs -mkdir /wordcount/hdfs dfs -put wordcount
摘要由CSDN通过智能技术生成

WordCount

需求: 在一堆给定的文本文件中统计输出每一个单词出现的总次数

Step 1. 数据格式准备
  1. 创建一个新的文件
cd /export/servers
vim wordcount.txt
  1. 向其中放入以下内容并保存
hello,world,hadoop
hive,sqoop,flume,hello
kitty,tom,jerry,world
hadoop
  1. 上传到 HDFS
hdfs dfs -mkdir /wordcount/
hdfs dfs -put wordcount.txt /wordcount/

Step 2. Mapper
public class WordCountMapper extends Mapper<LongWritable,Text,Text,LongWritable> {
   
    @Override
    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
   
        String line = value.toString();
        String[] split = line.split(",");
        for (String word : split) {
   
            context.write(new Text(word),new LongWritable(1));
        }

    }
}
Step 3. Reducer
public class WordCountReducer extends Reducer<Text,LongWritable,Text,LongWritable> {
   
    /**
     * 自定义我们的reduce逻辑
     * 所有的key都是我们的单词,所有的values都是我们单词出现的次数
     * @param key
     * @param values
     * @param context
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
   
        long count = 0;
        for (LongWritable value : values) {
   
            count += value.get();
        }
        context.write(key,new LongWritable(count));
    }
}
Step 4. 定义主类, 描述 Job 并提交 Job
public class JobMain extends Configured implements Tool {
   
    @Override
    public int run(String[] args) throws Exception {
   
        Job job = Job.getInstance(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值