package com.abstractdatatype.hash;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;
import java.util.Map.Entry;
/*Hashtable的应用:统计海量数据中出现频率高的数据*/
public class ApplicationOfHashtable {
public static void main(String[] args) {
int A[]=new int [50];
for(int i=0;i<A.length;i++){
A[i]=(int)(Math.random()*10);
}
List<Entry<Integer,Integer>> list=ApplicationOfHashtable.getTop(A, 5);
for (Entry<Integer, Integer> entry : list) {
System.out.println("key: "+entry.getKey()+"-----> times: "+entry.getValue());
}
}
//最热门查询统计,统计每个query的次数,然后找到top n
public static List<Entry<Integer,Integer>> getTop(int [] A,int n){
//利用hashtable来统计每个查询出现的次数
Hashtable<Integer,Integer> table=new Hashtable<Integer,Integer>();
int times=1;
for(int i=0;i<A.length;i++){
if(table.size()==0){
table.put(A[i], times);
}else{
if(table.containsKey(A[i])){
times=table.get(A[i]);
table.put(A[i], times+1);
}else{
table.put(A[i], times);
}
}
}
ArrayList<Entry<Integer,Integer>> list=new ArrayList<Entry<Integer,Integer>>(table.entrySet());
//重写Comparator中的compare方法,排序规则:根据出现频率降序,同时根据key降序
Collections.sort(list,new Comparator<Entry<Integer,Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
if(o1.getValue().compareTo(o2.getValue())==0){
return o2.getKey().compareTo(o1.getKey());
}else{
return o2.getValue().compareTo(o1.getValue());
}
}
});
return list.subList(0, n);
}
}
Hashtable的应用:统计海量数据中出现频率高的数据
最新推荐文章于 2024-11-06 09:01:20 发布