Java对字符串中字符出现的次数进行排序
时间:2011-02-01 csdn博客 赵学庆
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
|