Java Program to Count the Occurrences of Each Character Using HashMap

Ramesh Fadatare
2 min readDec 13, 2024

--

Introduction

Counting the occurrences of each character in a string is a common task in text processing. Using a HashMap allows you to efficiently store and update the frequency of characters. This guide will walk you through writing a Java program that counts the occurrences of each character in a given string using a HashMap.

Problem Statement

Create a Java program that:

  • Prompts the user to enter a string.
  • Uses a HashMap to count the occurrences of each character in the string.
  • Displays each character along with its count.

Example:

  • Input: "hello"
  • Output: h: 1 e: 1 l: 2 o: 1

Solution Steps

  1. Read the String: Use the Scanner class to take the string as input from the user.
  2. Initialize a HashMap: Use a HashMap to store each character of the string as keys and their counts as values.
  3. Iterate Through the String: Loop through each character in the string and update the count in the map.
  4. Display the Character Counts: Print each character along with its count.
  5. Close Resources: Close the Scanner class object automatically using the try-resource statement.

Java Program

// Java Program to Count the Occurrences of Each Character Using HashMap

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CharacterCountUsingHashMap {
public static void main(String[] args) {
// Step 1: Read the string from the user
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Step 2: Initialize the HashMap
Map<Character, Integer> charCountMap = new HashMap<>();

// Step 3: Iterate through the string and update the HashMap
for (char ch : input.toCharArray()) {
charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
}

// Step 4: Display the character counts
System.out.println("Character occurrences:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
}

Explanation

Step 1: Read the String

  • The Scanner class is used to read a string input from the user. The nextLine() method captures the entire line as a string.

Step 2: Initialize the HashMap

  • A HashMap is used to store each character as a key and its count as the value. This allows for efficient storage and retrieval of character counts.

Step 3: Iterate Through the String

  • A for loop iterates over each character in the string, converting the string to a character array using toCharArray().
  • The getOrDefault() method is used to check if the character already exists in the map. If it does, the count is incremented by 1; if not, the character is added to the map with an initial count of 1.

Step 4: Display the Character Counts

  • The program iterates through the HashMap entries and prints each character along with its count using System.out.println().

Output

Enter a string: hello
Character occurrences:
h: 1
e: 1
l: 2
o: 1

Conclusion

This Java program demonstrates how to count and display the occurrences of each character in a user-input string using a HashMap. It covers essential concepts such as string manipulation, using maps to store character counts, and iterating through collections, making it a valuable exercise for beginners learning Java programming.

--

--

No responses yet