单机版WordCount的代码实现

在学习MapReduce的时候,我们遇到的最经典的题目就是WordCount,也是相当于一个学习MapReduce的入门案例。相当于我们学习Java的时候关于HelloWord的编程实现。

这篇博客内容不多,主要分享一下单机版WordCount的代码实现,至于增强版的WordCount和其它有关于MapReduce的经典案例题目,笔者会在后面单独总结出来的。

首先,代码实现功能是:***统计6个文件里面的单词数量***。

以下是文件内容(6个文件的内容相同。)

代码实现如下:

package LearningSelf;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

//统计6个文件的每个单词出现的总次数
/*
 * 1.分而治之   map
 * 创建6个流  每个流负责读取一个文件  统计这个文件的每个单词的次数
 * 2.合并上面的统计结果  进行最终的统计  reduce
 */
public class WordCount {
	public static void main(String[] args) throws IOException {
		Map<String, Integer> file01map = readOneFile("D:\\wc\\wc01.txt");
		Map<String, Integer> file02map = readOneFile("D:\\wc\\wc02.txt");
		Map<String, Integer> file03map = readOneFile("D:\\wc\\wc03.txt");
		Map<String, Integer> file04map = readOneFile("D:\\wc\\wc04.txt");
		Map<String, Integer> file05map = readOneFile("D:\\wc\\wc05.txt");
		Map<String, Integer> file06map = readOneFile("D:\\wc\\wc06.txt");
		System.out.println(file01map);
		System.out.println(file02map);
		System.out.println(file03map);
		System.out.println(file04map);
		System.out.println(file05map);
		System.out.println(file06map);
		//汇总统计,
		Map<String, Integer> resultMap=mergeAllFile(file01map,file02map,file03map,file04map,file05map,file06map);
		System.out.println(resultMap);
	}
	//汇总统计最终的结果
	public static Map<String, Integer> mergeAllFile(Map<String, Integer> ... maps) {
		//结果集
		Map<String,Integer> resmap=new HashMap<String,Integer>();
		//循环每一个map
		for(Map<String, Integer> m:maps){
			//循环遍历每一个map
			Set<String> keys = m.keySet();
			for(String k:keys){
				//判断结果集中是否已经包含  
				//没有包含  直接放入
				if(!resmap.containsKey(k)){
					resmap.put(k, m.get(k));
				}else{
					//包含  将原来的值拿出+现在的值
					int newvalue=resmap.get(k)+m.get(k);
					resmap.put(k, newvalue);
				}
				
			}
		}
		return resmap;
	}
	//分而治之  统计每一个文件的
	public static Map<String,Integer> readOneFile(String path) throws IOException{
		//创建一个输入流  
		BufferedReader br=new BufferedReader(new FileReader(path));
		//开始进行文件的读取
		//创建一个统计的容器
		Map<String,Integer> map=new HashMap<String,Integer>();
		String line=null;
		while((line=br.readLine())!=null){
			//获取的是每一行的单词数组
			String[] words = line.split("\t");
			//循环遍历所有的单词  进行统计  容器---map<string,count>
			for(String w:words){
				//判断单词是否已经放入过
				//没有放入    key=w   value=1
				if(!map.containsKey(w)){
					map.put(w, 1);
				}else{
					//存在 value 取出原来的  +1
					int newvalue=map.get(w)+1;
					map.put(w, newvalue);
				}
			}
		}
		return map;
	}
	

}

运行结果如下:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值