Java program to count the occurrence of each character in a string using Hashmap

Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string.

Examples:

Input: str = "GeeksForGeeks"
Output:
r 1
s 2
e 4
F 1
G 2
k 2
o 1

Input: str = "Ajit" 
Output: 
A 1
t 1
i 1
j 1 

An approach using frequency[] array has already been discussed in the previous post. In this program an approach using Hashmap in Java has been discussed.

  • Declare a Hashmap in Java of {char, int}.
  • Traverse in the string, check if the Hashmap already contains the traversed character or not.
  • If it is present, then increase its count using get() and put() function in Hashmap.
  • Once the traversal is completed, traverse in the Hashmap and print the character and its frequency.

Below is the implementation of the above approach.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java prorgam to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
    static void characterCount(String inputString)
    {
        // Creating a HashMap containing char
        // as a key and occurrences as  a value
        HashMap<Character, Integer> charCountMap
            = new HashMap<Character, Integer>();
  
        // Converting given string to char array
  
        char[] strArray = inputString.toCharArray();
  
        // checking each char of strArray
        for (char c : strArray) {
            if (charCountMap.containsKey(c)) {
  
                // If char is present in charCountMap,
                // incrementing it's count by 1
                charCountMap.put(c, charCountMap.get(c) + 1);
            }
            else {
  
                // If char is not present in charCountMap,
                // putting this char to charCountMap with 1 as it's value
                charCountMap.put(c, 1);
            }
        }
  
        // Printing the charCountMap
        for (Map.Entry entry : charCountMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        String str = "Ajit";
        characterCount(str);
    }
}

chevron_right


Output:

A 1
t 1
i 1
j 1


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.