020-003-009

Word Counter with HashMap

Easy

Problem Description

Word Counter with HashMap

In this problem: You will create a program that uses HashMap<String, Integer> to count word occurrences in a predefined array of words and display each word with its count, sorted alphabetically.

Learning Objective: Understand basic HashMap operations (put, get, containsKey) and how to traverse entries

Overview

Manage the occurrence count of each word in a string array using a HashMap. Implement adding/updating values in the map and displaying entries sorted by key.

Specifications

Main Class (Main.java)

  1. Define the following word array: {"apple", "banana", "apple", "cherry", "banana", "apple", "date", "cherry"}
  2. Create a HashMap<String, Integer>
  3. Traverse the array and count occurrences of each word
    • If the word is not in the map, add it with count 1
    • If the word is already in the map, increment the count by 1
  4. Sort words alphabetically and display them
    • Format: "word: count" (one word per line)
  5. Finally display the number of unique words (format: "Unique words: count")

Output Format

apple: 3
banana: 2
cherry: 2
date: 1
Unique words: 4

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