hashMap=newHashMap<>();for(inti=myStr.length()-1; i>=0;i--){ if(hashMap.conta"/> hashMap=newHashMap<>();for(inti=myStr.length()-1; i>=0;i--){ if(hashMap.conta">

Home >Java >javaTutorial >Java program to count occurrences of each character

Java program to count occurrences of each character

WBOY
WBOYforward
2023-08-26 23:05:091276browse

Java program to count occurrences of each character

Suppose the following is our string -

String myStr = "thisisit";

To count the number of occurrences, we use a HashMap. Loop and use containsKey(0 and charAt() methods to count the number of 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

The following is the program to count the number of 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  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}

The above is the detailed content of Java program to count occurrences of each character. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete