English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java program to check the occurrence of each character in a String

To find the occurrence of each character in a string, we can use Java's Map utility. In the Map, keys cannot be repeated, so each character in the string is used as the key of the Map and the initial value corresponding to each key is provided as if this character has not been inserted into the mapping before.1. Now, when a character is repeated during insertion, its value will increase as the key in the Map. Continue this operation for each character until all characters of the inserted string are processed.

Example

public class occurenceOfCharacter {
   public static void main(String[] args) {
      String str = "SSDRRRTTYYTYTR";
      HashMap<Character, Integer> hMap = new HashMap<>();
      for (int i = str.length() - 1; i >= 0; i--) {
         if (hMap.containsKey(str.charAt(i))) {
            int count = hMap.get(str.charAt(i));
            hMap.put(str.charAt(i), ++count);
         } else {
            hMap.put(str.charAt(i),1);
         }
      }
      System.out.println(hMap);
   }
}

Output Result

{D=1, T=4, S=2, R=4, Y=3}