GeeksforGeeks App
Open App
Browser
Continue

# 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.

## Java

 `// Java program to count frequencies of``// characters in string using Hashmap``import` `java.io.*;``import` `java.util.*;``class` `OccurrenceOfCharInString {``    ``static` `void` `characterCount(String inputString)``    ``{``        ``// Creating a HashMap containing char``        ``// as a key and occurrences as  a value``        ``HashMap charCountMap``            ``= ``new` `HashMap();` `        ``// 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);``    ``}``}`

Output:

```A 1
t 1
i 1
j 1```

Time complexity: O(n) where n is length of given string

Auxiliary Space: O(n)

My Personal Notes arrow_drop_up