/**
* 给定一个字符串,统计个个字符串出现的频率
* @param s
*/
public static void tongji(String s){
HashMap<Character, Integer> hashCache = new HashMap<Character, Integer>();
for(int i=0;i<s.length();i++){
char _c = s.charAt(i);
if(hashCache.containsKey(_c)){
hashCache.put(_c,hashCache.get(_c)+1);
}else{
hashCache.put(_c, 1);
}
}
Set<Character> keys = hashCache.keySet();
for(Character c:keys){
// System.out.println("字符"+c+"出现的次数为"+hashCache.get(c));
}
Set<Entry<Character, Integer>> ss =hashCache.entrySet();
ArrayList<Entry<Character, Integer>> mappingList = new ArrayList<Entry<Character, Integer>>();
mappingList.addAll(ss);
Comparator cp = new Comparator<Map.Entry<String,Integer>>(){
public int compare(Map.Entry<String,Integer> mapping1,Map.Entry<String,Integer> mapping2){
return mapping2.getValue().compareTo(mapping1.getValue());
}
};
Collections.sort(mappingList, cp);
for(Entry<Character, Integer> entry:mappingList){
System.out.println("字符"+entry.getKey()+"出现的次数为"+entry.getValue());
}
}
给定一个字符串,统计每个字符串出现的频率,并排序
最新推荐文章于 2022-10-21 17:35:50 发布