To count the occurrence of each character in a string using Hashmap, the Java code is as follows −
Example
import java.io.*; import java.util.*; public class Demo{ static void count_characters(String input_str){ HashMap<Character, Integer> my_map = new HashMap<Character, Integer>(); char[] str_array = input_str.toCharArray(); for (char c : str_array){ if (my_map.containsKey(c)){ my_map.put(c, my_map.get(c) + 1); }else{ my_map.put(c, 1); } } for (Map.Entry entry : my_map.entrySet()){ System.out.println(entry.getKey() + " " + entry.getValue()); } } public static void main(String[] args){ String my_str = "Joe Erien "; System.out.println("The occurence of every character in the string is "); count_characters(my_str); } }
Output
The occurence of every character in the string is 2 r 1 e 2 E 1 i 1 J 1 n 1 o 1
A class named Demo contains the function named ‘count_characters’. Here, a hashmap is created that will store the character and its count. This function iterates through the string and checks for the count of every character. In the main function, the string is defined, and the function is called on this string and relevant message is displayed on the console.