首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 字符串字符頻率統計與排序:HashMap 計數 + Collections.sort 實現

     編輯:Java 相關知識

需求描述

統計字符串中每個字符出現次數,按頻率降序排序輸出。

核心算法

  1. 遍歷字符串,用 HashMap 計數
  2. 將 Map 值轉為 List
  3. 實現 Comparable 定義排序規則(按 count 降序)
  4. 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

優化與擴展

Java 8+ 流式寫法

String str = "...";
Map freq = str.chars()
    .mapToObj(c -> (char) c)
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

freq.entrySet().stream()
    .sorted(Map.Entry.comparingByValue().reversed())
    .forEach(e -> System.out.println(e.getKey() + "=" + e.getValue()));
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
場景優化方案
超長字符串用 int[65536] 數組替代 Map(字符範圍固定)
需穩定排序次要鍵加入字符碼:return other.count != this.count ? other.count - this.count : this.ch - other.ch;
並行處理Java 8+ str.chars().parallel()... 流式統計
Unicode 輔助平面用 codePointAt 處理補充字符