hadoop的WordCount按照value降序排序

package demo2;

import java.io.IOException;
import java.util.Random;
import java.util.StringTokenizer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
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.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.map.InverseMapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class WordCount2 {
    public static class TokenizerMapper extends
            Mapper<Object, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();
        private String pattern = "[^//w]"; // 正则表达式,代表不是0-9, a-z, A-Z的所有其它字符,其中还有下划线
        public void map(Object key, Text value, Context context)
                throws IOException, InterruptedException {
            String line = value.toString().toLowerCase(); // 全部转为小写字母
           // line = line.replaceAll(pattern, " "); // 将非0-9, a-z, A-Z的字符替换为空格
            StringTokenizer itr = new StringTokenizer(line);
            int i=0;
            while (itr.hasMoreTokens()) {
            	i++;
            	if(i ==20)
            		break;
            	
                word.set(itr.nextToken());
                context.write(word, one);
            }
        }
    }
    public static class IntSumReducer extends
            Reducer<Text, IntWritable, Text, IntWritable> {
        private IntWritable result = new IntWritable();
        public void reduce(Text key, Iterable<IntWritable> values,
                Context context) throws IOException, InterruptedException {
            int sum = 0;
            
            for (IntWritable val : values) {
                sum += val.get();
            }
            result.set(sum);
            context.write(key, result);
        }
    }
    
     private static class IntWritableDecreasingComparator extends IntWritable.Comparator {
          public int compare(WritableComparable a, WritableComparable b) {
            return -super.compare(a, b);
          }
          
          public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
              return -super.compare(b1, s1, l1, b2, s2, l2);
          }
      }
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        String[] otherArgs = new GenericOptionsParser(conf, args)
                .getRemainingArgs();
        if (otherArgs.length != 2) {
            System.err.println("Usage: wordcount <in> <out>");
            System.exit(2);
        }
         Path tempDir = new Path("wordcount-temp-" + Integer.toString(
                    new Random().nextInt(Integer.MAX_VALUE))); //定义一个临时目录
        
        Job job = new Job(conf, "word count");
        job.setJarByClass(WordCount2.class);
        try{
            job.setMapperClass(TokenizerMapper.class);
            job.setCombinerClass(IntSumReducer.class);
            job.setReducerClass(IntSumReducer.class);
            
            job.setOutputKeyClass(Text.class);
            job.setOutputValueClass(IntWritable.class);
            
            FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
            FileOutputFormat.setOutputPath(job, tempDir);//先将词频统计任务的输出结果写到临时目
                                                         //录中, 下一个排序任务以临时目录为输入目录。
            job.setOutputFormatClass(SequenceFileOutputFormat.class);
            if(job.waitForCompletion(true))
            {
                Job sortJob = new Job(conf, "sort");
                sortJob.setJarByClass(WordCount2.class);
                
                FileInputFormat.addInputPath(sortJob, tempDir);
                sortJob.setInputFormatClass(SequenceFileInputFormat.class);
                
                /*InverseMapper由hadoop库提供,作用是实现map()之后的数据对的key和value交换*/
                sortJob.setMapperClass(InverseMapper.class);
                /*将 Reducer 的个数限定为1, 最终输出的结果文件就是一个。*/
                sortJob.setNumReduceTasks(1); 
                FileOutputFormat.setOutputPath(sortJob, new Path(otherArgs[1]));
                
                sortJob.setOutputKeyClass(IntWritable.class);
                sortJob.setOutputValueClass(Text.class);
                /*Hadoop 默认对 IntWritable 按升序排序,而我们需要的是按降序排列。
                 * 因此我们实现了一个 IntWritableDecreasingComparator 类, 
                 * 并指定使用这个自定义的 Comparator 类对输出结果中的 key (词频)进行排序*/
                sortJob.setSortComparatorClass(IntWritableDecreasingComparator.class);
     
                System.exit(sortJob.waitForCompletion(true) ? 0 : 1);
            }
        }finally{
            FileSystem.get(conf).deleteOnExit(tempDir);
        }
    }
}

启动

./sbin/start-dfs.sh

删除原来的输出文件(文件存在会报错)

./bin/hdfs dfs -rm -r /user/output

运行(user/input里有输入文件)

./bin/hadoop jar z.jar /user/input /user/output


查看结果

 ./bin/hdfs dfs -text /user/output/part-r-00000

关闭

./sbin/stop-dfs.sh

我注释了过滤的部分

欢迎批评指导

转载自:

https://www.cnblogs.com/xwdreamer/archive/2011/01/07/2297044.html

 

 

 

 

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hadoop WordCount是一个经典的MapReduce程,用于对文本数据进行词频统计。实现方法如下: 1. Map阶段:将文本数据按照指定的分隔符进行切分,将每个单词作为Key,将频率作为Value传递给Reduce阶段。 2. Reduce阶段:将Map阶段传递过来的Key-Value对进行合并,统计每个单词在文本中出现的次数,输出最终的词频统计结果。 以下是Hadoop WordCount的Java代码示例: ```java public class WordCount { public static class TokenizerMapper extends Mapper<Object, Text, Text, IntWritable>{ private final static IntWritable one = new IntWritable(1); private Text word = new Text(); public void map(Object key, Text value, Context context) throws IOException, InterruptedException { StringTokenizer itr = new StringTokenizer(value.toString()); while (itr.hasMoreTokens()) { word.set(itr.nextToken()); context.write(word, one); } } } public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> { private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } result.set(sum); context.write(key, result); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "word count"); job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } } ``` 以上代码中,TokenizerMapper类实现了Map阶段的逻辑,IntSumReducer类实现了Reduce阶段的逻辑,main函数用于配置和提交MapReduce作业。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值