Java Data Type How to - Count Chars in a String








Question

We would like to know how to count Chars in a String.

Answer

import java.util.Map;
import java.util.TreeMap;
/*w  w w  .  j  a v a  2s.c o m*/
public class Main{
  public static void main(String[] args) {
    String yourString = "UNDERSTAND";
    Map<Character, Integer> count = new TreeMap<Character, Integer>();
    for (char c : yourString.toCharArray()) {
      if (count.containsKey(c)) {
        count.put(c, (int) count.get(c) + 1);
      } else {
        count.put(c, 1);
      }
    }
    System.out.println(count);
  }
}