MapReduceTopK TreeMap
版权声明: https://blog.csdn.net/zhangxiango/article/details/33319281
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
* zhangxian1991@qq.com
*/
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
*zhangxian1991@qq.com
*/
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的更多相关文章
- HashMap与TreeMap源码分析
1. 引言 在红黑树--算法导论(15)中学习了红黑树的原理.本来打算自己来试着实现一下,然而在看了JDK(1.8.0)TreeMap的源码后恍然发现原来它就是利用红黑树实现的(很惭愧学了Ja ...
- 计算机程序的思维逻辑 (43) - 剖析TreeMap
40节介绍了HashMap,我们提到,HashMap有一个重要局限,键值对之间没有特定的顺序,我们还提到,Map接口有另一个重要的实现类TreeMap,在TreeMap中,键值对之间按键有序,Tree ...
- Collections+Iterator 接口 | Map+HashMap+HashTable+TreeMap |
Collections+Iterator 接口 1. Collections 是一个操作 Set.List 和 Map 等集合的工具类 Collections 中提供了大量方法对集合元素进行排序.查询 ...
- 【集合框架】JDK1.8源码分析之TreeMap(五)
一.前言 当我们需要把插入的元素进行排序的时候,就是时候考虑TreeMap了,从名字上来看,TreeMap肯定是和树是脱不了干系的,它是一个排序了的Map,下面我们来着重分析其源码,理解其底层如何实现 ...
- 容器--TreeMap
一.概述 在Map的实现中,除了我们最常见的KEY值无序的HashMap之外,还有KEY有序的Map,比较常用的有两类,一类是按KEY值的大小有序的Map,这方面的代表是TreeMap,另外一种就保持 ...
- Java之TreeMap
基本特性: 基于红黑树. 非线程安全. 同步使用: SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...))
- Map接口,Map.Entry,hashMap类,TreeMap类,WeakHashMap。
Collection接口之前接触过,每次保存的对象是一个对象,但是在map中保存的是一对对象,是以key->value形式保存的. 定义: public interface Map<K,V ...
- Java 集合类 TreeSet、TreeMap
TreeMap和TreeSet的异同: 相同点: TreeMap和TreeSet都是有序的集合,也就是说他们存储的值都是拍好序的. TreeMap和TreeSet都是非同步集合,因此他们不能在多线程之 ...
- 【转】HashMap、TreeMap、Hashtable、HashSet和ConcurrentHashMap区别
转自:http://blog.csdn.net/paincupid/article/details/47746341 一.HashMap和TreeMap区别 1.HashMap是基于散列表实现的,时间 ...
随机推荐
- Phaser实现源代码剖析
Phaser是一个能够反复利用的同步栅栏.功能上与CyclicBarrier和CountDownLatch相似,只是提供更加灵活的使用方法.也就是说,Phaser的同步模型与它们几乎相同. 一般运用的 ...
- html块级元素与内联元素的区别
1. 块级元素(block element): 概念理解:如果不用css控制,块级元素在文档流中以一行显示,及它所占的宽度为其父级元素所占的宽度,若超过宽度会重新另起一行显示,高度会随着内容高度的增 ...
- nginx源码学习_数据结构(ngx_str_t)
nginx中关于字符串的数据结构位于src/core/ngx_string.c和src/core/ngx_string.h中 先来看一下数据结构: typedef struct { size_t le ...
- linux系统之free命令详解
total used free shared buffers cached Mem: -/+ buffers/cache: Swap: 上面是free命令的执行结果,下面我来详细说说其中的含义: Me ...
- JPA动态查询封装
一.定义一个查询条件容器 /** * 定义一个查询条件容器 * * @param <T> */ public class Criteria<T> implements Spec ...
- 青蛙的约会 扩展欧几里得 方程ax+by=c的整数解 一个跑道长为周长为L米,两只青蛙初始位置为x,y;(x!=y,同时逆时针运动,每一次运动分别为m,n米;问第几次运动后相遇,即在同一位置。
/** 题目:青蛙的约会 链接:https://vjudge.net/contest/154246#problem/R 题意:一个跑道长为周长为L米,两只青蛙初始位置为x,y:(x!=y,同时逆时针运 ...
- Fantasy of a Summation n个数,k层重复遍历相加。求它的和%mod的值;推导公式+快速幂
/** 题目:Fantasy of a Summation 链接:https://vjudge.net/contest/154246#problem/L 题意:n个数,k层重复遍历相加.求它的和%mo ...
- 【问题】CentOS6.5系统"libc.so.6: version 'GLIBC_2.15' not found"解决方法
出现"libc.so.6: version 'GLIBC_2.15' not found"问题,是由于glibc版本过低,升级glibc即可. 由于CentOS系统RPM源目前gl ...
- 基于python的七种经典排序算法(转)
一.排序的基本概念和分类 所谓排序,就是使一串记录,按照其中的某个或某些关键字的大小,递增或递减的排列起来的操作.排序算法,就是如何使得记录按照要求排列的方法. 排序的稳定性:经过某种排序后,如果两个 ...
- faceswap
https://github.com/deepfakes/faceswap https://anonfile.com/p7w3m0d5be