Build a Word Frequency Counter in Java
A practical Java guide for counting how often each word appears in text, including normalization, case handling, splitting rules and limitations.
What does a word frequency counter do for your text?
A word frequency counter reads text, splits it into words, and reports how many times each word occurs. The result is usually a map from a word to its count. In Java, the natural output type is a Map whose keys are words and whose values are integer counts. The exact meaning of "word" depends on how you split the input and how you normalize it.
Start with a simple split-based counter
The simplest approach is to split the input on whitespace and add each resulting piece to a map. This handles ordinary prose where words are separated only by spaces, tabs or newlines.
Example input: "cat dog cat" would be split into "cat", "dog" and "cat". Counting those pieces gives cat 2 and dog 1.
| Step,What happens\nRead input,The full string to analyze\nSplit on whitespace,The string becomes separate word-like pieces\nAdd each piece to a map,The count increments for each occurrence\nReturn the map,Words become keys and occurrence totals become values |
Normalize case to merge the same word
By default, "Java" and "java" are different keys. If your intended result is a meaningful word count, convert each piece to lowercase before counting. This merges words that differ only by capitalization.
Example input: "Java java JAVA" would become keys for three different strings without normalization. With lowercase conversion, all three occurrences count under the single key "java".
Remove punctuation so words are words
A whitespace-only split leaves punctuation attached. For example, "java." is not the same as "java". To count the intended word rather than the punctuation-marked variant, split on sequences of characters that are not letters or digits. In Java, you can use an expression that matches one or more non-word characters as the separator.
Example input: "Hello, hello!" contains two text forms before normalization. Splitting on non-word characters and converting to lowercase counts both pieces as "hello".
A complete Java implementation
The following example combines splitting, lowercase normalization, punctuation removal and counting in one method.
import java.util.HashMap;\nimport java.util.Map;\n\npublic class WordFrequencyCounter {\n public Map<String, Integer> countWords(String text) {\n Map<String, Integer> counts = new HashMap<>();\n String trimmed = text == null ? "" : text.trim();\n if (trimmed.isEmpty()) {\n return counts;\n }\n\n String[] words = trimmed.toLowerCase().split("[^\p{L}\p{N}]+");\n for (String word : words) {\n counts.put(word, counts.getOrDefault(word, 0) + 1);\n }\n return counts;\n }\n}
The split pattern in this example treats a separator as one or more characters that are not Unicode letters or digits. It is an illustrative pattern, not a verified output claim: the exact behavior depends on the Java version and the Unicode properties supported by the regular expression engine.
Why the split pattern matters
A pattern based on non-word characters has important limitations. Hyphenated words such as "e-mail" become two words. Contractions such as "don't" become "don" and "t". Accented or non-Latin text may be handled differently depending on whether the pattern uses Unicode letter and number categories or a narrower word-character definition.
If apostrophes or hyphens should stay inside a word, you need a different splitting rule. A tokenization strategy should be chosen to match the kind of text you are processing.
Java and JavaScript are different tasks
The same idea is available in JavaScript, but the implementation is a separate language task. A JavaScript word frequency counter uses string methods or regular expressions and a plain object or Map, with its own Unicode and splitting rules. Java language features and JavaScript syntax cannot be used interchangeably.
Watch for gaps and assumptions
- Empty input: the example returns an empty map rather than a map containing an empty key.;Null input: handling is explicit in the example by treating null as empty text.;Unicode digits and letters: the example uses Unicode categories, but compatibility should be tested for your target Java version.;Stop words: words such as "the" and "and" are still counted unless you explicitly remove them.;Documented behavior versus assumption: the example code illustrates the intended approach; its output has not been presented here as verified test results.