建立一個通用的頻率統計工具類,使用泛型 T 代表待統計資料型別,要求 T 正確實作 equals() 與 hashCode() 方法。核心功能包含:關鍵字統計、取得所有鍵值對、取得所有 Key 集合、查詢單一 Key 統計值。
package com.zj.col;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class Statistics<T> {
private Map<T, Integer> m = new HashMap<T, Integer>();
/** 統計關鍵字出現次數 */
public void statistics(T t) {
Integer freq = m.get(t);
m.put(t, freq == null ? 1 : freq + 1);
}
/** 返回底層 Map (所有鍵值對) */
public void getAllKeysStatistics() {
System.out.println(m);
}
/** 返回所有 Key 組成的 Set */
public void getAllKeys() {
System.out.println(m.keySet());
}
/** 返回單一 Key 的統計值,不存在回傳 0 */
public int getKeyStatistics(T t) {
return m.get(t) == null ? 0 : m.get(t);
}
public static void main(String[] args) {
Random rand = new Random();
Statistics<Integer> s = new Statistics<Integer>();
// 產生 10000 個 0-9 隨機整數進行統計
for (int i = 0; i < 10000; i++) {
int r = rand.nextInt(10); // 0-9
s.statistics(r);
}
s.getAllKeysStatistics();
s.getAllKeys();
System.out.println("Key -1:" + s.getKeyStatistics(-1)); // 不存在的 Key
System.out.println("Key 0:" + s.getKeyStatistics(0));
}
}
{0=1038, 1=1014, 2=939, 3=987, 4=977, 5=974, 6=1036, 7=974, 8=1075, 9=986}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Key -1:0
Key 0:1038
使用 <T> 使工具類可統計任意型別資料 (Integer、String、自訂物件等),唯一要求是 T 必須正確實作 equals() 與 hashCode(),確保 HashMap 能正確判斷鍵值相等。
Integer freq = m.get(t);
m.put(t, freq == null ? 1 : freq + 1);
先查詢現有頻率,若為 null (首次出現) 設為 1,否則遞增。避免了 computeIfAbsent 或 merge 等 Java 8+ 方法的相容性問題,適用於舊版 Java 環境。
getKeyStatistics() 方法處理 Key 不存在情況,回傳 0 而非 null,避免呼叫端發生 NullPointerException。
Statistics<String> wordStats = new Statistics<>();
String text = "hello world hello java";
for (String word : text.split("\\s+")) {
wordStats.statistics(word);
}
wordStats.getAllKeysStatistics(); // {hello=2, world=1, java=1}
class User {
String name; int age;
// 建構子、getter、equals、hashCode...
}
Statistics<User> userStats = new Statistics<>();
userStats.statistics(new User("Alice", 25));
userStats.statistics(new User("Bob", 30));
userStats.statistics(new User("Alice", 25)); // 同一使用者
userStats.getAllKeysStatistics(); // {User[Alice,25]=2, User[Bob,30]=1}
ConcurrentHashMap 替換 HashMap,配合 merge() 或 compute() 實現無鎖統計stream() 方法支援函數式操作 (排序、過濾、Top-N 查詢)