// 第 11 周 – 用内置的哈希表（HashMap）统计频率
// 运行：java WordCount.java
import java.util.*;

public class WordCount {
    public static void main(String[] args) {
        String text = "the quick brown fox jumps over the lazy dog the fox runs and the dog sleeps";

        Map<String, Integer> freq = new HashMap<>();
        for (String w : text.split(" ")) freq.merge(w, 1, Integer::sum); // freq[w]++
        System.out.println("frequencies: " + freq);

        // 出现次数最多的 3 个单词：按值对 map 的条目排序
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(freq.entrySet());
        entries.sort((a, b) -> b.getValue() - a.getValue());
        System.out.println("top 3: " + entries.subList(0, 3));

        // 其他操作
        System.out.println("containsKey(\"fox\") = " + freq.containsKey("fox") + ", get(\"cat\") = " + freq.get("cat")
                + ", getOrDefault(\"cat\", 0) = " + freq.getOrDefault("cat", 0));

        // TreeMap：按键排序（平衡二叉搜索树）
        System.out.println("sorted: " + new TreeMap<>(freq));

        // hashCode：每个 Java 对象都有；String 的 hashCode 是多项式哈希（基数 31）
        System.out.println("\"Li\".hashCode() = " + "Li".hashCode() + " = 'L'·31 + 'i' = " + ('L' * 31 + 'i'));
    }
}
