public static void main(String[] args) {
charCount("abadcdffbaeba");
}
public static String charCount(String str) {
char[] chs = str.toCharArray();
TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
for (int x = 0; x < chs.length; x++) {
Integer value = tm.get(chs[x]);
if (value == null) {
tm.put(chs[x], 1);
} else {
value = value + 1;
tm.put(chs[x], value);
}
}
Set<Character> keySet = tm.keySet();
Iterator<Character> it = keySet.iterator();
int i = 0;
while (it.hasNext()) {
Character key = it.next();
Integer value = tm.get(key);
System.out.println(key + "::::" + value);
}
//把TreeMap对象的entrySet()做成List,然后用Collections类的sort方法排序的,
//而且要用带比较器参数的那个sort,并且比较器要重写compare方法,实现value的比较
List arrayList = new ArrayList(tm.entrySet());
Collections.sort(arrayList, new Comparator() {
public int compare(Object o1, Object o2) {
Map.Entry obj1 = (Map.Entry) o1;
Map.Entry obj2 = (Map.Entry) o2;
return ((Integer) obj2.getValue()).compareTo((Integer) obj1
.getValue());
}
});
System.out.println(arrayList);
return null;
} |