Exercise · Map, Set and JSON · lesson 7 of 9
Exercise: word frequency in a Map
Write a function function wordFrequency(text) that returns a Map: its keys are the words of the string text, and its values are how many times each word occurs. The keys must follow the order in which the words first appear in the string.
wordFrequency("the cat and the hat")→ aMapwith the pairsthe → 2,cat → 1,and → 1,hat → 1wordFrequency("b a b c a b")→ aMapwith the pairsb → 3,a → 2,c → 1wordFrequency("")→ an emptyMap
Constraints: words consist of lowercase Latin letters and are separated by one space, with no spaces at the start or the end of the string; for the empty string the result is an empty Map whose size is 0.
The tests first check that the result is a Map: got instanceof Map is true only for a Map.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.