编写mapreduce程序实现对输入文件的词频统计排序_MapReduce实例分析:单词计数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是MapReduce程序的实现步骤: 1. Map阶段:将每一行作为一个记录,以该行中的某个字段作为key,整行作为value输出。 2. Shuffle阶段:根据Map输出的key值进行分组,将同一个key值的value分到同一个Reduce Task中。 3. Reduce阶段:对每一个Reduce Task中的记录按照key进行排序,输出排序后的结果。 以下是MapReduce程序的实现代码: Map阶段: ```java public static class SortMapper extends Mapper<LongWritable, Text, Text, Text> { private Text outKey = new Text(); private Text outValue = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] strs = value.toString().split(","); outKey.set(strs[0]); // 以第一个字段作为key outValue.set(value.toString()); context.write(outKey, outValue); } } ``` Reduce阶段: ```java public static class SortReducer extends Reducer<Text, Text, Text, NullWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { List<String> list = new ArrayList<String>(); for (Text value : values) { list.add(value.toString()); } Collections.sort(list); // 对记录按照key进行排序 for (String value : list) { context.write(new Text(value), NullWritable.get()); } } } ``` 需要注意的是,以上代码只实现了升序排序,如需实现降序排序,只需将Collections.sort(list)改为Collections.reverse(list)即可。 另外,在提交MapReduce程序之前,需要设置Job的输入路径、输出路径、Mapper和Reducer等信息,以下是完整代码: ```java public class SortJob { public static class SortMapper extends Mapper<LongWritable, Text, Text, Text> { private Text outKey = new Text(); private Text outValue = new Text(); public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] strs = value.toString().split(","); outKey.set(strs[0]); // 以第一个字段作为key outValue.set(value.toString()); context.write(outKey, outValue); } } public static class SortReducer extends Reducer<Text, Text, Text, NullWritable> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { List<String> list = new ArrayList<String>(); for (Text value : values) { list.add(value.toString()); } Collections.sort(list); // 对记录按照key进行排序 for (String value : list) { context.write(new Text(value), NullWritable.get()); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "SortJob"); job.setJarByClass(SortJob.class); job.setMapperClass(SortMapper.class); job.setReducerClass(SortReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值