020-003-008
Counting Word Occurrences with HashMap
Medium
Problem Description
Counting Word Occurrences with HashMap
In this problem, you will create a method that uses HashMap<String, Integer> to count word occurrences.
Learning Objective: Understand aggregation with HashMap and the use of getOrDefault
Overview
Implement a countWords method that takes a space-separated string of words, counts occurrences of each word, and returns a formatted string sorted by count descending (alphabetical for ties).
Specifications
- Define
countWords(String sentence)method - Split the input string by spaces using
split(" ") - Count each word using
HashMap<String, Integer>withgetOrDefault - Sort by count descending (alphabetical for ties)
- Return a newline-separated string in
"word: count"format
Example
countWords("apple banana apple cherry banana apple")
→ "apple: 3\nbanana: 2\ncherry: 1"
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up