Java Program to Find Frequency of Each Character in a String

Previous
Next

In this tutorial, we will see simple program to find frequency of Each Character in a String.
There are multiple ways to solve this proble. Let’s see one by one.

Using counter array

Here is the algorithm for the same.

  • Initialize counter array of 256 length
  • Iterate over String and increase count by 1 at index based on Character. For example: If we encounter ‘a’ in String, it will be like counter[97]++ as ASCII value of ‘a’ is 97.
  • Iterate over counter array and print character and frequency if counter[i] is not 0.

Output:

Enter a String : Java2Blog
The character B has occurred for 1 times
The character J has occurred for 1 times
The character a has occurred for 2 times
The character g has occurred for 1 times
The character l has occurred for 1 times
The character o has occurred for 1 times
The character v has occurred for 1 times

Using HashMap

We can use HashMap as well to find Frequency of Each Character in a String.

  1. Create a HashMap which will contain character to count mapping.
  2. Iterate over String
  3. make count to 1 if HashMap do not contain the character and put it in HashMap with key as Character and count as value
  4. If HashMap already have the character, increment its count by 1

Output:

{a=2, 2=1, b=1, v=1, g=1, j=1, l=1, o=1}

Using HashMap’s computeIfPresent and computeIfAbsent[java 8]

We can also use HashMap’s computeIfPresent and computeIfAbsent to write code in more functional way. It uses Java 8‘s lambda expressions to write the logic.
Let’s rewrite the code as below.

It will generate same output as above program.
That’s all about Java Program to Find Frequency of Each Character in a String.

Previous
Next

Add Comment