MapReduce实现单词统计

任务:MapReduce实现一个单词统计程序。给定输入文件夹,对该文件夹中所有文件单词出现次数进行统计。

file1.txt:

hello world
bye world

file2.txt:

hello hadoop
bye hadoop

file3.txt:

conte

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

public class WordCount {
	// map
	protected static class WordCountMap extends Mapper<LongWritable, Text, Text, IntWritable> {
		@Override
		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			String[] strs = value.toString().split(" ");
			for (String str : strs) {
				context.write(new Text(str), new IntWritable(1));
			}
		}
	}
	// reduce
	protected static class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values, Context context)
				throws IOException, InterruptedException {
			int sum = 0;
			for (IntWritable val : values) {
				sum += val.get();

			}
			context.write(key, new IntWritable(sum));
		}
	}

	public static void main(String[] args) throws IOException, ClassNotFoundException, Exception {
		Configuration conf=new Configuration();    
		Path inpath=new Path("hdfs://192.168.109.125:8020/input/");  
		Path outpath=new Path("hdfs://192.168.109.125:8020/output/");  
		Job job=Job.getInstance(conf);    
		job.setJarByClass(WordCount.class);   
		job.setOutputKeyClass(Text.class);   
		job.setOutputValueClass(IntWritable.class);   
		job.setMapperClass(WordCountMap.class);     
		job.setReducerClass(WordCountReducer.class);   
		FileInputFormat.addInputPath(job, inpath);     
		FileOutputFormat.setOutputPath(job, outpath);  
		job.waitForCompletion(true); 

	}
}

 输出结果:

bye    2
content    1
hadoop    2
hello    2
world    2

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值