【java】用HashMap计数,用TreeSet排序

 package com.tn.hashMap;

 import java.util.HashMap;
import java.util.TreeSet; public class HashMapDemo {
public static void main(String[] args){ String str="eeeeaccbbddddffffff";
HashMap<String,Integer> hashMap=new HashMap<String,Integer>();
for(int i=0;i<str.length();i++){
if(!hashMap.containsKey(str.substring(i, i+1))){
hashMap.put(str.substring(i, i+1), 1);
}else{
hashMap.put(str.substring(i,i+1), hashMap.get(str.substring(i, i+1))+1);
}
} TreeSet<T> treeSet=new TreeSet<T>();
for(String key:hashMap.keySet()){
T t=new T(key,hashMap.get(key));
treeSet.add(t);
}
System.out.println(treeSet);
}
} class T implements Comparable<T>{
private String value;
private Integer count; public T(String value, Integer count) {
super();
this.value = value;
this.count = count;
} public String getValue() {
return value;
} public void setValue(String value) {
this.value = value;
} public Integer getCount() {
return count;
} public void setCount(Integer count) {
this.count = count;
} @Override
public String toString() {
return value+"出现"+count+"次。";
} @Override
public int compareTo(T o) {
if(this.count!=o.count)
return this.count-o.count;//以出现次数排序
else
return this.value.compareTo(o.value);//出现次数相同以字母顺序排序
} }
上一篇:Redis 的Lua Script脚本功能


下一篇:YII千万级PV架构经验分享--理论篇