Java Data Type How to - Check character occurrence in a string








Question

We would like to know how to check character occurrence in a string.

Answer

import java.util.HashMap;
import java.util.Map;
//from w w w  .  j a v a2 s .c om
public class Main {
  public static void main(String[] args) {
    Map<Character, Integer> counting = new HashMap<Character, Integer>();
    String testcase1 = "this is a test";
    for (char ch : testcase1.toCharArray()) {
      Integer freq = counting.get(ch);
      counting.put(ch, (freq == null) ? 1 : freq + 1);
    }
    System.out.println(counting.size() + " distinct characters:");
    System.out.println(counting);
  }

}