How To Count Occurrences Of Each Character In String

Using Java

To find the number of occurrences of each character in a given string, we have used HashMap with character as a key and it’s occurrences as a value. First, we convert the given string to char array and check each character one by one. And update it’s count in HashMap.

import java.util.HashMap;
 
public class EachCharCountInString
{
    private 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 'c' is present in charCountMap, incrementing it's count by 1
  
                charCountMap.put(c, charCountMap.get(c)+1);
            }
            else
            {
                //If char 'c' is not present in charCountMap,
                //putting 'c' into charCountMap with 1 as it's value
  
                charCountMap.put(c, 1);
            }
        }
         
        //Printing inputString and charCountMap 
  
        System.out.println(inputString+" : "+charCountMap);
    }
  
    public static void main(String[] args)
    {
       characterCount("Java J2EE Java JSP J2EE");
  
       characterCount("All Is Well");
  
       characterCount("Done And Gone");
    }
}
Output :

Java J2EE Java JSP J2EE : { =4, P=1, a=4, 2=2, S=1, E=4, v=2, J=5}
All Is Well : { =2, A=1, s=1, e=1, W=1, I=1, l=4}
Done And Gone : { =2, A=1, D=1, d=1, e=2, G=1, n=3, o=2}