Count the occurrence of each character in a string using Java program

Contents

Count frequency of each character in a String

In some cases, we want to check the occurrence of each character in a string. Based on the occurrence, we might decide our further logic building in the real word applications.

Example : revisitclass

r – 1
e – 1
v – 1
i – 2
t – 1
c – 1
l – 1
a – 1
s – 3

Java program to calculate the occurrence of each character

  • Since Hashmap allows to store the key and value pairs in java, we are using the same to store the each character (key) and its frequency (value).
  • Get method in Hashmap – It is used to retrieve the value from the hashmap.
  • Put method in Hashmap – It is used to add the key & value pair in the hashmap.
  • The string value is converted to Character array so that we can iterate each character using for loop.
  • If the character is already present in the hashmap, we just increment the value.
  • If the character is not present in the hashmap, we add the character as key and the value as 1.
import java.util.HashMap;
import java.util.Map;

public class CountCharacter {
    public static void main(String[] args) {
        //input String
        String input = "revisitclass";
        int startingValue=1;

        //Creating a hashmap to store character as a key and occurrence as a value
        Map<Character,Integer> charWithcount = new HashMap<>();

        char[] inputCharArray = input.toCharArray();

        // iterate each character from characterArray
      for(Character eachChar : inputCharArray){

          //condition is true if the character is already present in the map
          if(charWithcount.containsKey(eachChar)){
              //increment the character occurrence in the map
              //Hashmap doesn't allow duplicate keys so it increments the value alone
              charWithcount.put(eachChar,charWithcount.get(eachChar)+1);
          }else{
              // put the new character in the map with starting value as 1
              charWithcount.put(eachChar,startingValue);
          }

      }
      for(Character inputChar : charWithcount.keySet()){
          //search for value using character
          Integer count = charWithcount.get(inputChar);

          // print each character and its occurrence
          System.out.println( inputChar + ": " + count);
      }
    }
}

Output

a: 1
r: 1
s: 3
c: 1
t: 1
e: 1
v: 1
i: 2
l: 1