How To Count Occurrences Of Each Character In String In Java?



import java.util.HashMap;

public class CountCharInStringJavaInHouse
{
  
   public static void main(String[] args)
    {
       countCharacter("How many number each character is there in string using hashmap");
    }
    static void countCharacter(String inputString)
    {
        
        HashMap<Character, Integer> resultMap = new HashMap<Character, Integer>();
        
        char[] strArray = inputString.toCharArray();

        for (char c : strArray)
        {
          
          if(resultMap.containsKey(c) )
            {

                resultMap.put(c, resultMap.get(c)+1);
            }
            else
            {


                resultMap.put(c, 1);
            }
          
        }

        System.out.println(resultMap);
    }
   
}

OutPut:
Occurrences Of Each Character In String

Post a Comment