Java Data Type How to - Count frequency of characters in a string








Question

We would like to know how to count frequency of characters in a string.

Answer

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*  www.j ava2 s.  c om*/
public class Main {
  public static void main(String[] args) {
    String input = "this is a test";
    frequenceyCount(input);
  }
  private static void frequenceyCount(String input) {
    Map<Character, Integer> hashCount = new HashMap<>();
    Character c;
    for (int i = 0; i < input.length(); i++) {
      c = input.charAt(i);
      if (hashCount.get(c) != null) {
        hashCount.put(c, hashCount.get(c) + 1);
      } else {
        hashCount.put(c, 1);
      }
    }
    Iterator it = hashCount.entrySet().iterator();
    System.out.println("char : frequency");
    while (it.hasNext()) {
      Map.Entry pairs = (Map.Entry) it.next();
      System.out.println(pairs.getKey() + " : " + pairs.getValue());
      it.remove();
    }
  }
}