手机版
你好,游客 登录 注册
背景:
阅读新闻

Hadoop 统计单词字数的例子

[日期:2012-05-18] 来源:Linux社区  作者:supercharles [字体:大 中 小]

Hadoop 的核心还是 Map-Reduce过程和 hadoop分布式文件系统

第一步:定义Map过程

  1. /** 
  2.  * 
  3.  * Description: 
  4.  * 
  5.  * @author charles.wang 
  6.  * @created Mar 12, 2012 1:41:57 PM 
  7.  *  
  8.  */ 
  9. public class MyMap extends Mapper<Object, Text, Text, IntWritable> { 
  10.      
  11.     private static final IntWritable one = new IntWritable(1); 
  12.     private Text word; 
  13.      
  14.      
  15.     public void map(Object key ,Text value,Context context)  
  16.             throws IOException,InterruptedException{ 
  17.          
  18.         String line=value.toString(); 
  19.         StringTokenizer tokenizer = new StringTokenizer(line); 
  20.         while(tokenizer.hasMoreTokens()){ 
  21.             word = new Text(); 
  22.             word.set(tokenizer.nextToken()); 
  23.             context.write(word, one); 
  24.         } 
  25.          
  26.     } 
  27.  
  28. } 

第二步: 定义 Reduce 过程

  1. /** 
  2.  * 
  3.  * Description: 
  4.  * 
  5.  * @author charles.wang 
  6.  * @created Mar 12, 2012 1:48:18 PM 
  7.  *  
  8.  */ 
  9. public class MyReduce extends Reducer<Text, IntWritable, Text, IntWritable> { 
  10.      
  11.     public void reduce (Text key,Iterable<IntWritable> values,Context context) 
  12.         throws IOException ,InterruptedException{ 
  13.          
  14.         int sum=0; 
  15.         for(IntWritable val: values){ 
  16.             sum+=val.get(); 
  17.         } 
  18.          
  19.         context.write(key, new IntWritable(sum)); 
  20.     } 
  21.  
  22. } 
linux
相关资讯       Hadoop配置 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款