統計字符串中每個字符出現次數,按頻率降序排序輸出。
HashMap 計數ListComparable 定義排序規則(按 count 降序)Collections.sort() 執行排序import java.util.*;
public class CharFrequencySort {
public static void main(String[] args) {
String str = "12345678hfdjkslahfkj932189oiefsjkar94werfdsf";
Map map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
KeyValue kv = map.get(c);
if (kv == null) {
kv = new KeyValue();
kv.ch = c;
kv.count = 1;
map.put(c, kv);
} else {
kv.count++;
}
}
List list = new ArrayList<>(map.values());
Collections.sort(list); // 依賴 KeyValue.compareTo
for (KeyValue o : list) {
System.out.println(o.ch + "=" + o.count);
}
}
}
class KeyValue implements Comparable {
char ch;
int count;
public int compareTo(KeyValue other) {
return other.count - this.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
| 場景 | 優化方案 |
|---|---|
| 超長字符串 | 用 int[65536] 數組替代 Map(字符範圍固定) |
| 需穩定排序 | 次要鍵加入字符碼:return other.count != this.count ? other.count - this.count : this.ch - other.ch; |
| 並行處理 | Java 8+ str.chars().parallel()... 流式統計 |
| Unicode 輔助平面 | 用 codePointAt 處理補充字符 |