DEV Community

Abhishek Kumar
Abhishek Kumar

Posted on

Write a Java program to count the frequency of characters in a string using HashMap.

Here’s a Java program that counts the frequency of each character in a string using a HashMap:

Java Program to Count Character Frequency in a String:

import java.util.HashMap;

public class CharacterFrequency {
    public static void main(String[] args) {
        // Input string
        String input = "frequency of characters";

        // Create a HashMap to store character frequencies
        HashMap<Character, Integer> charCountMap = new HashMap<>();

        // Convert string to lowercase for case-insensitive counting (optional)
        input = input.toLowerCase();

        // Loop through each character in the string
        for (char c : input.toCharArray()) {
            // Ignore spaces (optional)
            if (c != ' ') {
                // If the character is already present in the map, increment its count
                if (charCountMap.containsKey(c)) {
                    charCountMap.put(c, charCountMap.get(c) + 1);
                } else {
                    // Otherwise, add the character with a count of 1
                    charCountMap.put(c, 1);
                }
            }
        }

        // Print the character frequencies
        System.out.println("Character Frequency:");
        for (HashMap.Entry<Character, Integer> entry : charCountMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Input: The string "frequency of characters".
  • HashMap<Character, Integer>: Stores each character as a key and its frequency as the corresponding value.
  • Logic:
    • The program iterates over each character in the string.
    • If the character is not already in the HashMap, it adds it with a count of 1.
    • If the character is already in the HashMap, it increments the count by 1.
    • Spaces are ignored in this example.
  • Output: The program will output the frequency of each character in the string.

Sample Output:

Character Frequency:
f: 2
r: 3
e: 3
q: 1
u: 1
n: 1
c: 3
y: 1
o: 1
a: 2
t: 2
h: 1
s: 1
Enter fullscreen mode Exit fullscreen mode

This program demonstrates how to use a HashMap to efficiently count the frequency of characters in a string.

Top comments (0)