Hadoop之Mapreduce------>入门级程序WordCount代码编写

一 、Mapper编写

继承Mapper类------>重写map方法------>实现具体业务逻辑------>将新的key,value输出


public class WCMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //接收数据V1

        String line = value.toString();

//按照空格切分成单词

        String[] words = line.split(" ");
        for (String w : words) {
            //出现一次记1
            context.write(new Text(w), new LongWritable(1));
        }
    }
}

一 、Reducer编写

继承Reducer类------>重写reduce方法------>实现具体业务逻辑------>将新的key,value输出


public class WCReducer extends Reducer<Text,LongWritable,Text,LongWritable> {
    @Override
    protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
        //接受数据
//        Text k3 = key;
        //定义一个计数器

        long counter = 0;

       //遍历values集合,并求和

        for(LongWritable i:values){
            counter += i.get();

        }

       //将新的key,value输出

        context.write(key,new LongWritable(counter));
    }
}

三 、主函数编写


public class WordCount {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        //构建job类
        Job job = Job.getInstance(new Configuration());

        //注意main方法所在的类,别忘记设置setJarByClass
        job.setJarByClass(WordCount.class);

        //设置mapper相关属性
        job.setMapperClass(WCMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);


//设置源文件

        FileInputFormat.setInputPaths(job,new Path("/wordcount"));

        //设置Rueduce相关属性
        job.setReducerClass(WCReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);


//设置输出文件

        FileOutputFormat.setOutputPath(job,new Path("/wcout126"));

        //提交任务
        job.waitForCompletion(true);
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值