Count the occurrence of each character in a string using Java program

Count frequency of each character in a String

In some cases, we want to check the occurrence of each character in a string. Based on the occurrence, we might decide our further logic building in the real word applications.

Example : revisitclass

r – 1
e – 1
v – 1
i – 2
t – 1
c – 1
l – 1
a – 1
s – 3

Java program to calculate the occurrence of each character

  • Since Hashmap allows to store the key and value pairs in java, we are using the same to store the each character (key) and its frequency (value).
  • Get method in Hashmap – It is used to retrieve the value from the hashmap.
  • Put method in Hashmap – It is used to add the key & value pair in the hashmap.
  • The string value is converted to Character array so that we can iterate each character using for loop.
  • If the character is already present in the hashmap, we just increment the value.
  • If the character is not present in the hashmap, we add the character as key and the value as 1.

Output