# 简介
用 MapReduce 实现 wordCount(单词计数)
软件 2004-20207127 云计算作业
# 相关类
# WordCountMapper
| package org.example; |
| |
| import org.apache.hadoop.io.IntWritable; |
| import org.apache.hadoop.io.LongWritable; |
| import org.apache.hadoop.io.Text; |
| import org.apache.hadoop.mapreduce.Mapper; |
| import java.io.IOException; |
| |
| public class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable> { |
| |
| @Override |
| protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { |
| System.out.println(key); |
| String line=value.toString(); |
| String[] words=line.split(" "); |
| for(String word : words){ |
| context.write(new Text(word),new IntWritable(1)); |
| } |
| } |
| } |
# WordCountReduce
| package org.example; |
| |
| import org.apache.hadoop.io.IntWritable; |
| import org.apache.hadoop.io.Text; |
| import org.apache.hadoop.mapreduce.Reducer; |
| import java.io.IOException; |
| |
| public class WordCountReduce extends Reducer<Text, IntWritable,Text,IntWritable> { |
| @Override |
| protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { |
| int total=0; |
| for(IntWritable value : values){ |
| total+=value.get(); |
| } |
| context.write(key,new IntWritable(total)); |
| } |
| } |
# WordCountMain
| package org.example; |
| |
| import org.apache.hadoop.conf.Configuration; |
| import org.apache.hadoop.fs.Path; |
| import org.apache.hadoop.io.IntWritable; |
| import org.apache.hadoop.io.Text; |
| import org.apache.hadoop.mapreduce.Job; |
| import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; |
| import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; |
| |
| import java.io.IOException; |
| |
| public class WordCountMain { |
| public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException { |
| |
| Configuration cfg=new Configuration(); |
| Job job=Job.getInstance(cfg,"wc"); |
| job.setJarByClass(WordCountMain.class); |
| |
| job.setMapperClass(WordCountMapper.class); |
| job.setReducerClass(WordCountReduce.class); |
| |
| job.setMapOutputKeyClass(Text.class); |
| job.setMapOutputValueClass(IntWritable.class); |
| |
| |
| job.setOutputKeyClass(Text.class); |
| job.setMapOutputValueClass(IntWritable.class); |
| |
| FileInputFormat.setInputPaths(job,new Path("S:/test/data.txt")); |
| FileOutputFormat.setOutputPath(job,new Path("S:/test/M")); |
| |
| boolean result=job.waitForCompletion(true); |
| System.out.println(result?"成功":"失败"); |
| System.exit(result?0:1); |
| } |
| } |
# 运行结果