Start learning free

LESSON 225 OF 671 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Frequency in Java: Counting Words with split and HashMap

Practice Read the full explanation

Given a string sentence, count how many times each word appears in it. Return a HashMap where each word of the sentence is a key, and its value is the number of times that word appears.

The words are in lower case and separated by single spaces, and the sentence has at least one word. The order of the entries doesn't matter.

Example 1:

Input: sentence = "the cat and the hat"
Output: {"the": 2, "cat": 1, "and": 1, "hat": 1}
Explanation: "the" appears twice. Every other word appears once.

Example 2:

Input: sentence = "go go go"
Output: {"go": 3}
Explanation: The same word three times gives one key, "go", with the value 3.

Example 3:

Input: sentence = "hello"
Output: {"hello": 1}
Explanation: A sentence of one word: that word appears once.
STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Frequency in Java, explained

    Problem overview

    The method wordFrequency receives a string, sentence, made of lower-case words separated by single spaces. It returns a HashMap<String, Integer> where each distinct word is a key and its value is how many times the word appears.

    For "the cat and the hat" the result is {the=2, and=1, cat=1, hat=1}: "the" appears twice and every other word once. For "go go go" it is {go=3}, one key with the value 3. A sentence of one word, "hello", gives {hello=1}. The order of the entries doesn't matter.

    Approach: split, then count

    There are two jobs. First, turn the sentence into separate words. Second, count them with a map, the same way you count letters of a word: a word already in the map has its count raised by one, and a new word enters with 1.

    The first job is one method call. sentence.split(" ") cuts the string at every space and returns a String[]. For "the cat" it returns an array with the two elements the and cat. Because the lesson guarantees single spaces between words and no other characters, each piece is exactly one word.

    Step by step

    1. Split the sentence into a String[] named words.
    2. Create the empty map. HashMap<String, Integer> counts = new HashMap<>(); holds the words as keys and the counts as values. Nothing has been counted yet.
    3. Loop over the words with an enhanced for loop, one String word per pass.
    4. Known word: if counts.containsKey(word), put it back with counts.get(word) + 1. put on an existing key replaces the old value.
    5. New word: in the else, put it with the value 1.
    6. Return the map after the loop.

    The solution in Java

    class Solution {
        public HashMap<String, Integer> wordFrequency(String sentence) {
            String[] words = sentence.split(" ");
            HashMap<String, Integer> counts = new HashMap<>();
            for (String word : words) {
                if (counts.containsKey(word)) {
                    counts.put(word, counts.get(word) + 1);
                } else {
                    counts.put(word, 1);
                }
            }
            return counts;
        }
    }
    

    Java details worth knowing:

    • split takes a pattern. The argument is a regular expression. A single space has no special meaning in one, so " " works exactly as it reads. Characters such as . or | do have special meanings and would need escaping.
    • Why not call get directly. get returns null for a missing key, and adding 1 to null throws a NullPointerException. The containsKey check avoids it. counts.put(word, counts.getOrDefault(word, 0) + 1) is a compact alternative.
    • String keys compare by content. A HashMap finds keys with equals and hashCode, so two different String objects holding the same characters are the same key. You don't need to think about == here.
    • The printed form. A map prints as {key=value, ...}, with no quotes around the words. The order is up to the HashMap.

    Tracing the first example

    This is the map after each word of "the cat and the hat" has been handled:

    the -> {the=1}
    cat -> {the=1, cat=1}
    and -> {the=1, and=1, cat=1}
    the -> {the=2, and=1, cat=1}
    hat -> {the=2, and=1, cat=1, hat=1}
    

    Only the second "the" finds its key already present and raises the count to 2. Every other word creates a new entry.

    Reading the result

    Once you have the map, get answers "how many times?" for one word. On the first example, get("the") is 2, and get("dog") is null, because a word that never appeared has no entry. To go through every entry, loop over entrySet() and read getKey() and getValue() from each one.

    Words are compared exactly. The statement promises lower case, but for a sentence like "The the" the map is {The=1, the=1}: two different keys. Calling toLowerCase() on the sentence first would merge them.

    Complexity

    Time: O(n) for a sentence of n characters. Splitting reads the string once, and each word then costs a constant number of map operations on average, plus the time to hash the word, which depends on its length.

    Space: O(n) in the worst case, for the array of words and the map, which has an entry per distinct word.

    Why a map and not a list

    You could keep a list of words and, for each new word, scan the list to find it. That makes every word cost time proportional to the number of different words so far. A HashMap finds a key directly from its hash code, so a lookup doesn't grow with the size of the map in the typical case. For a long text, the difference is large.

    The same shape of solution counts anything you can split into pieces: split on a comma to count items in a list, or split a log line on spaces to count its fields. Only the argument of split and the key type of the map change.

    Edge cases and common mistakes

    • More than one space. The lesson promises single spaces. If a sentence had two in a row, split(" ") would produce an empty string between them: "a b" gives {=1, a=1, b=1}, with an empty-string key. Splitting on the pattern "\\s+" handles runs of spaces.
    • Forgetting the else. Without it, a new word never gets an entry, or every count is reset.
    • A one-word sentence. "hello".split(" ") returns an array with one element, so the result is {hello=1}.
    • Expecting an order. Don't depend on the order of the entries.

    Testing

    • "the cat and the hat" gives {the=2, and=1, cat=1, hat=1}.
    • "go go go" gives {go=3}.
    • "hello" gives {hello=1}.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free