How to count frequency of each character in a string in Java

In this article, we will write a Java program to calculate the frequency/occurrence of character in a String in Java.

Since we need to create a structure to hold both a character and a number, we can create a Map for the same.

Here, the character will be the key and its frequency will be the value.
 
Now, to find the frequency, we can loop through each character in the String and check if the character is already present in the map. If its already present, we increment the count by 1, else we will initialize the count to 1.
 
Here is the code for the same :

    char[] charArray = str.toCharArray();
  for (char c : charArray) {
    Integer count = charFreqMap.get(c);
    // increment count if character already exists in map, else set
    // count to 1
    int newCount = (count == null ? 1 : count + 1);
    charFreqMap.put(c, newCount);
  }

 
Here is the complete program :

package com.topjavatutorial;

import java.util.HashMap;
import java.util.Map;

public class CharacterCountinString {

  public static void main(String[] args) {
    String str = "HelloWorld";
    characterCount(str);
  }

  private static void characterCount(String str) {
    // Map with char as key and frequency as value
    Map<Character, Integer> charFreqMap = new HashMap<Character, Integer>();

    if (str != null) {
      char[] charArray = str.toCharArray();
      for (char c : charArray) {
        Integer count = charFreqMap.get(c);
        // increment count if character already exists in map, else set
        // count to 1
        int newCount = (count == null ? 1 : count + 1);
        charFreqMap.put(c, newCount);
      }
    }
    System.out.println(charFreqMap);
  }
}

Output :


{r=1, d=1, e=1, W=1, H=1, l=3, o=2}

 

© 2016 – 2017, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags