Let’s say the following is our string −
String myStr = "thisisit";
To count the occurrences, we are using HashMap. Loop through and using containsKey(0 and charAt() method, count the occurrences of each character in the above string −
HashMap <Character, Integer> hashMap = new HashMap<>(); for (int i = myStr.length() - 1; i >= 0; i--) { if (hashMap.containsKey(myStr.charAt(i))) { int count = hashMap.get(myStr.charAt(i)); hashMap.put(myStr.charAt(i), ++count); } else { hashMap.put(myStr.charAt(i),1); } }
Example
Following is the program to count the occurrences of each character −
import java.util.HashMap; public class Demo { public static void main(String[] args) { String myStr = "thisisit"; System.out.println("String ="+myStr); HashMap <Character, Integer> hashMap = new HashMap<>(); for (int i = myStr.length() - 1; i >= 0; i--) { if (hashMap.containsKey(myStr.charAt(i))) { int count = hashMap.get(myStr.charAt(i)); hashMap.put(myStr.charAt(i), ++count); } else { hashMap.put(myStr.charAt(i),1); } } System.out.println("Counting occurrences of each character = "+hashMap); } }
Output
String =thisisit Counting occurrences of each character = {s=2, t=2, h=1, i=3}