import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 對字符集中字符出現的次數繼續排序。
*
* @author 趙學慶
*/
public class T {
public static void main(String args[]) {
String str = "12345678hfdjkslahfkj932189oiefsjkar94werfdsf";
Map<Character, KeyValue> map = new HashMap<Character, KeyValue>();
char c;
KeyValue kv = null;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
kv = map.get(c);
if (kv == null) {
kv = new KeyValue();
kv.ch = c;
kv.count = 1;
map.put(c, kv);
} else {
kv.count++;
}
}
List<KeyValue> list = new ArrayList<KeyValue>(map.values());
Collections.sort(list);
for (KeyValue o : list) {
System.out.println(o.ch + "=" + o.count);
}
}
}
class KeyValue implements Comparable {
public int compareTo(Object obj) {
if (obj instanceof KeyValue) {
KeyValue kv = (KeyValue) obj;
return kv.count - this.count;
}
return -1;
}
char ch;
int count;
}
運行結果
f=5
j=3
k=3
s=3
9=3
d=2
e=2
a=2
h=2
3=2
2=2
1=2
r=2
4=2
8=2
o=1
l=1
i=1
w=1
7=1
6=1
5=1