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

  1. Define countWords(String sentence) method
  2. Split the input string by spaces using split(" ")
  3. Count each word using HashMap<String, Integer> with getOrDefault
  4. Sort by count descending (alphabetical for ties)
  5. 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