Wednesday, January 3, 2024

Count Number of Times Each Character Appears in a String Java Program

In this post we'll see a Java program to count the total number of times each character occurs in the given String. Here three ways are given for counting the occurrences of each character in the given String;

  1. Program using HashMap
  2. Program using char array
  3. Program using Java Stream

Counting the frequency of characters in String using HashMap

Here it is done using HashMap provided by Java Collection framework. Logic is to read one character at a time from the string and put it in HashMap; character as key, count as value (Initial value will be 1).

With every character that is read from the String check in the HashMap, if it already exists as a key or not. If it exists then increment the count otherwise add the key in HashMap with value 1.

public class CountCharacters {    
  // method used to count characters in a String
  public void countChars(String message){
    Map<Character, Integer> numCharMap = new HashMap<Character, Integer>();
    for(int i = 0; i < message.length(); i++){
      // Take one character 
      char c = message.charAt(i);
      // We don't need to count spaces
      if(c == ' ')
        continue;
      // If that character is already there in the map
      // then increase the value by 1
      if(numCharMap.containsKey(c)){
        numCharMap.put(c, numCharMap.get(c) + 1);
      }else{
        // otherwise put that character in the map
        // with the value as 1
        numCharMap.put(c, 1);
      }
    }
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> numSet = numCharMap.entrySet();
    for(Map.Entry<Character, Integer> m : numSet){
      System.out.println("Char- " + m.getKey() + " Count " + m.getValue());
    }
  }
    
  public static void main(String[] args) {
    CountCharacters cc = new CountCharacters();
    cc.countChars("I am an Indian");
  }
}

Output

Char- a Count 3
Char- d Count 1
Char- I Count 2
Char- i Count 1
Char- m Count 1
Char- n Count 3

Values are displayed by looping the HashMap, entrySet is used to iterate the map, which gives the key value pair as Entry object.

Counting the frequency of characters in String using char array

In the Java program to count total number of occurrences of each character in a String using char array, given String is converted to char array then you need to iterate the array starting from first index and check if that character is found again in the char array. If yes then increase the count. One thing you need to do is to remove all the occurrences of that character from the string after counting is done for that specific character.

public class CountCharacters {
  public static void main(String[] args) {
    CountCharacters cc = new CountCharacters();
    cc.countChars("I am an Indian");
  }
    
  public void countChars(String str){
    char[] strArr;
    while(str.length() != 0){
      strArr = str.toCharArray();
      char ch = strArr[0];
      int count = 1;
      for(int i = 1; i < strArr.length; i++){
        if(ch == strArr[i]){
          count++;
        }
      }
      // We don't need to count spaces
      if(((ch != ' ') && (ch != '\t'))){
        System.out.println(ch + " - " + count);
      }
      // replace all occurrence of the character 
      // which is already iterated and counted
      str = str.replace(""+ch, "");
    }    
  }
}
Output
I - 2
a - 3
m - 1
n - 3
d - 1
i - 1

Counting the frequency of characters in String using Java Stream

In this way, String array that is returned by the split method is used to create a Stream using Stream.of() method. Then Collectors.groupingBy() of Java Stream API is used to group characters of the String and Collectors.counting() is also passed to perform a reduction operation. Collectors.groupingBy() returns a Map (key is char, value is count in our case) which is again iterated by getting the Set view of the Map using entrySet() method. filter() method is used to remove space character.

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CountCharacters {

  public static void main(String[] args) {
    String str = "I am an Indian";
    Stream.of(str.trim().split(""))
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet()
          .stream()
          .filter(e -> !e.getKey().equals(" "))
          .forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));
  }
}

Output

a - 3
d - 1
i - 1
I - 2
m - 1
n - 3

That's all for this topic Count Number of Times Each Character Appears in a String Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Count Number of Words in a String Java Program
  2. Java Program to Find The Longest Palindrome in a Given String
  3. Add Double Quotes to a String Java Program
  4. How to Reverse a String in Java
  5. Convert String to Byte Array Java Program

You may also like-

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  3. Access Modifiers in Java - Public, Private, Protected and Default
  4. Marker Interface in Java
  5. How LinkedList Class Works Internally in Java
  6. Functional Interfaces in Java
  7. ConcurrentSkipListMap in Java With Examples
  8. Dependency Injection in Spring Framework