Video in progress

How do you count how many times each word occurs in a text?

I split the text into words and write them to a HashMap<String, Integer> with merge(word, 1, Integer::sum). With streams, Collectors.groupingBy(w -> w, Collectors.counting()) works too. Time is O(n).

📖 Answer

static Map<String, Integer> countWords(String text) {
    Map<String, Integer> freq = new HashMap<>();
    for (String w : text.toLowerCase().split("\\W+")) {
        if (w.isEmpty()) continue;
        freq.merge(w, 1, Integer::sum);
    }
    return freq;
}

merge puts 1 if the key is missing and adds to the old value if it's there. The old style, if (map.containsKey(w)) ... else ..., does two lookups and is longer.

The stream version:

Map<String, Long> freq = Arrays.stream(text.toLowerCase().split("\\W+"))
        .filter(w -> !w.isEmpty())
        .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

Pay attention to two things. \\W+ treats only Latin letters and digits as part of a "word", so the Uzbek word o'g'il gets split at the apostrophes; change the regex if you need to. If the result has to come out in alphabetical order, use a TreeMap.