// Week 11 – Counting frequencies with the built-in hash table (HashMap)
// Run: 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);

        // The 3 most frequent words: sorting the entries of the map by value
        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));

        // Further operations
        System.out.println("containsKey(\"fox\") = " + freq.containsKey("fox") + ", get(\"cat\") = " + freq.get("cat")
                + ", getOrDefault(\"cat\", 0) = " + freq.getOrDefault("cat", 0));

        // TreeMap: sorted by key (balanced search tree)
        System.out.println("sorted: " + new TreeMap<>(freq));

        // hashCode: every Java object has one; that of String is polynomial (base 31)
        System.out.println("\"Li\".hashCode() = " + "Li".hashCode() + " = 'L'·31 + 'i' = " + ('L' * 31 + 'i'));
    }
}
