MapReduceTopK TreeMap

MapReduce TopK统计加排序中介绍的TopK在mapreduce的实现。

本案例省略的上面案例中的Sort步骤,改用TreeMap来实现获取前K个词

package TopK1;
import java.io.IOException;
import java.util.StringTokenizer;

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.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 统计词频
 * @author zx
 * [email protected]
 */
public class WordCount {

	/**
	 * 读取单词
	 * @author zx
	 *
	 */
	public static class Map extends Mapper<Object,Text,Text,IntWritable>{

		IntWritable count = new IntWritable(1);

		@Override
		protected void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			StringTokenizer st = new StringTokenizer(value.toString());
			while(st.hasMoreTokens()){
				String word = st.nextToken().replaceAll("\"", "").replace("'", "").replace(".", "");
				context.write(new Text(word), count);
			}
		}

	}

	/**
	 * 统计词频
	 * @author zx
	 *
	 */
	public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable>{

		@SuppressWarnings("unused")
		@Override
		protected void reduce(Text key, Iterable<IntWritable> values,Context context)
				throws IOException, InterruptedException {
			int count = 0;
			for (IntWritable intWritable : values) {
				count ++;
			}
			context.write(key,new IntWritable(count));
		}

	}

	@SuppressWarnings("deprecation")
	public static boolean run(String in,String out) throws IOException, ClassNotFoundException, InterruptedException{

		FileUtil.deleteFile(out);

		Configuration conf = new Configuration();

		Job job = new Job(conf,"WordCount1");
		job.setJarByClass(WordCount.class);
		job.setMapperClass(Map.class);
		job.setReducerClass(Reduce.class);

		// 设置Map输出类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        // 设置Reduce输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 设置输入和输出目录
        FileInputFormat.addInputPath(job, new Path(in));
        FileOutputFormat.setOutputPath(job, new Path(out));

        return job.waitForCompletion(true);
	}

}
package TopK1;

import java.io.IOException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeMap;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
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.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;

/**
 *
 * @author zx
 *[email protected]
 */
public class TopK {

	public static class TopKMap extends Mapper<Object, Text, IntWritable, IntWritable>{

		TreeMap<Integer,String> tm = new TreeMap<Integer,String>(new Comparator<Integer>() {

			/**
			 * treeMap中的元素逆序排列
			 * @param o1
			 * @param o2
			 * @return
			 */
			@Override
			public int compare(Integer o1, Integer o2) {
				return o2.compareTo(o1);
			}

		});
		int k = 0;

		@Override
		protected void cleanup(Context context) throws IOException,
				InterruptedException {
			Configuration conf = context.getConfiguration();
			Path topKPath = new Path(conf.get("topKOut"));
			FileSystem fs = topKPath.getFileSystem(conf);
			FSDataOutputStream fsDOS = fs.create(topKPath);
			Iterator<Integer> it = tm.keySet().iterator();
			while(it.hasNext()){
				Integer key = it.next();
				String value = tm.get(key).toString();
				String line = value + "\t" + key + "\r";
				fsDOS.write(line.getBytes(), 0, line.length());
			}
			fsDOS.flush();
			fsDOS.close();
		}

		@Override
		protected void setup(Context context) throws IOException,
				InterruptedException {
			k = Integer.parseInt(context.getConfiguration().get("K"));
		}

		@Override
		protected void map(Object key, Text value, Context context)
				throws IOException, InterruptedException {
			String[] parts = value.toString().split("\t");
			tm.put(Integer.parseInt(parts[1]),parts[0]);
			if(tm.size() > k){
				tm.remove(tm.lastKey());
			}
		}

	}

	@SuppressWarnings("deprecation")
	public static void main(String args[]) throws ClassNotFoundException, IOException, InterruptedException{

		if(args.length < 4){
			throw new IllegalArgumentException("要有4个参数:1,要统计的文本文件名。2,统计后的结果路径。3,topK的结果目录,4,K");
		}

		FileUtil.deleteFile(args[2]);

		//要统计字数的文本文件名
		String in = args[0];

		//统计字数后的结果
		String wordCount = args[1];

		in = FileUtil.loadFile(wordCount, "TopK1", in);

		//如果统计字数的job完成后就开始求topK
		if(WordCount.run(in, wordCount)){

			int k = Integer.parseInt(args[3]);
			Configuration conf = new Configuration();

			FileUtil.deleteFile(args[2]);
			conf.set("topKOut", args[2]);
			conf.set("K", k+"");

			Job job = new Job(conf,"TopK1");

			job.setJarByClass(TopK.class);
			job.setMapperClass(TopKMap.class);

			job.setOutputKeyClass(IntWritable.class);
			job.setOutputValueClass(IntWritable.class);

			FileInputFormat.addInputPath(job, new Path(wordCount));
			job.setOutputFormatClass(NullOutputFormat.class);

			System.exit(job.waitForCompletion(true)?0:1);
		}

	}

}
package TopK1;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/**
 *
 * @author zx
 *
 */
public class FileUtil {

	/**
	 * 上传数据文件到hdfs
	 * @param inputPath
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public static String loadFile(String inputPath,String folder,String fileName) throws IOException{

		//获取数据文件的全路径

		if(null != folder && !"".equals(folder)){
			folder = folder + "/";
		}

		String srcPathDir = FileUtil.class.getProtectionDomain().getCodeSource().getLocation()
                .getFile() + folder + fileName;

		Path srcpath = new Path("file:///" + srcPathDir);

		Path dstPath = new Path(getJobRootPath(inputPath) + fileName);

		Configuration conf = new Configuration();

		FileSystem fs = dstPath.getFileSystem(conf);

		fs.delete(dstPath, true);

		fs.copyFromLocalFile(srcpath, dstPath);

		fs.close();

		return getJobRootPath(inputPath) + fileName;
	}

	/**
	 * 如果路径的最后不包哈“/”就加一个“/”
	 * @param path
	 * @return
	 */
	public static String getJobRootPath(String path){
		if(path.lastIndexOf("/") == path.length()-1){
			path = path.substring(0, path.lastIndexOf("/"));
		}
		return path.substring(0, path.lastIndexOf("/")+1);
	}

	public static void deleteFile(String ...filePath) throws IOException{
		Configuration conf = new Configuration();
		for (int i = 0; i < filePath.length; i++) {
			Path path = new Path(filePath[i]);
			FileSystem fs = path.getFileSystem(conf);
			fs.delete(path,true);
		}
	}

}

MapReduceTopK TreeMap,布布扣,bubuko.com

时间: 2024-08-03 05:31:21

MapReduceTopK TreeMap的相关文章

HashMap与TreeMap源码分析

1. 引言     在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Java这么久,也写过一些小项目,也使用过TreeMap无数次,但到现在才明白它的实现原理).因此本着"不要重复造轮子"的思想,就用这篇博客来记录分析TreeMap源码的过程,也顺便瞅一瞅HashMap. 2. 继承结构 (1) 继承结构 下面是HashMap与TreeMap的继承结构: pu

深入理解 hash 函数、HashMap、LinkedHashMap、TreeMap 【中】

LinkedHashMap - 有序的 HashMap 我们之前讲过的 HashMap 的性能表现非常不错,因此使用的非常广泛.但是它有一个非常大的缺点,就是它内部的元素都是无序的.如果在遍历 map 的时候, 我们希望元素能够保持它被put进去时候的顺序,或者是元素被访问的先后顺序,就不得不使用 LinkedHashMap. LinkdHashMap 继承了 HashMap,因此,它具备了 HashMap 的优良特性-高性能.在HashMap 的基础上, LinkedHashMap 又在内部维

【源码】TreeMap源码剖析

注:以下源码基于jdk1.7.0_11 之前介绍了一系列Map集合中的具体实现类,包括HashMap,HashTable,LinkedHashMap.这三个类都是基于哈希表实现的,今天我们介绍另一种Map集合,TreeMap.TreeMap是基于红黑树实现的. 介绍TreeMap之前,回顾下红黑树的性质: 首先,我们要明确,红黑树是一种二叉排序树,而且是平衡二叉树.因而红黑树具有排序树的所有特点,任意结点的左子树(如果有的话)的值比该结点小,右子树(如果有的话)的值比该结点大.二叉排序树各项操作

Map:HashMap和TreeMap

一.Map集合     特点:将键映射到值得对象 Map集合和Collection集合的区别? Collection:是单列集合,存储的是单独出现的元素    Map: 是双列集合,存储的是键值对形式的元素 遍历方式:       方式一:通过键获取值                 hm.keySet();                 get(key)      方式二:通过键值对对象获取 键和值                hm.entrySet();               ge

Java 集合系列14之 Map总结(HashMap, Hashtable, TreeMap, WeakHashMap等使用场景)

http://www.cnblogs.com/skywang12345/p/3311126.html 概要 学完了Map的全部内容,我们再回头开开Map的框架图. 本章内容包括:第1部分 Map概括第2部分 HashMap和Hashtable异同第3部分 HashMap和WeakHashMap异同 转载请注明出处:http://www.cnblogs.com/skywang12345/admin/EditPosts.aspx?postid=3311126 第1部分 Map概括 (01) Map

hashMap,hashTable,hashSet,TreeMap的区别

[hashMap:](键值对,不同步,无序) 存放的是key-value的值,采用put方法:可以存相同的对象.是map的子类: 并允许使用 null 值和 null 键(除了非同步和允许使用 null 之外,HashMap 类与 Hashtable 大致相同.) 此类不保证映射的顺序,特别是它不保证该顺序恒久不变. 是无序的. 注意,此实现不是同步的. [hashTable:](对象,同步,无序) 为了成功地在哈希表中存储和获取对象,用作键的对象必须实现 hashCode 方法和 equals

TreeMap按照value进行排序

TreeMap底层是根据红黑树的数据结构构建的,默认是根据key的自然排序来组织(比如integer的大小,String的字典排序).所以,TreeMap只能根据key来排序,是不能根据value来排序的(否则key来排序根本就不能形成TreeMap). 今天有个需求,就是要根据treeMap中的value排序.所以网上看了一下,大致的思路是把TreeMap的EntrySet转换成list,然后使用Collections.sor排序.代码: [java] view plain copy publ

容器--TreeMap

一.概述 在Map的实现中,除了我们最常见的KEY值无序的HashMap之外,还有KEY有序的Map,比较常用的有两类,一类是按KEY值的大小有序的Map,这方面的代表是TreeMap,另外一种就保持了插入顺序的Map,这类的代表是LinkedHashMap. 本文介绍TreeMap. Java提供了两种可以用来排序的接口,分别是Comparable和Comparactor, 两者分别说明如下: 1. Comparable 目前这是一个泛型接口,只有一个方法compareTo,  参与比较的类需

Java 集合类 TreeSet、TreeMap

TreeMap和TreeSet的异同: 相同点: TreeMap和TreeSet都是有序的集合,也就是说他们存储的值都是拍好序的. TreeMap和TreeSet都是非同步集合,因此他们不能在多线程之间共享,不过可以使用方法Collections.synchroinzedMap()来实现同步 运行速度都要比Hash集合慢,他们内部对元素的操作时间复杂度为O(logN),而HashMap/HashSet则为O(1). 不同点: 最主要的区别就是TreeSet和TreeMap非别实现Set和Map接