Skip to content
Exercise · Collections and generics · lesson 13 of 13

Exercise: word frequency

Write a method static Map<String, Integer> countWords(String text) that returns a map: the key is a word of text, the value is how many times it occurs.

  • countWords("a b a") → {a=2, b=1}
  • countWords("hi") → {hi=1}
  • countWords("") → {}

Constraints: words are separated by exactly one space, with no spaces at the start or end of the string; uppercase and lowercase letters differ, so "A" and "a" are different words; an empty string gives an empty map.

Do not add extra imports unless the task says so explicitly.

Main.java — java
java · 9 lines
Ctrl+Enter run · Esc leave editor