Java Data Type How to - Count specific characters in a string








Question

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

Answer

import java.util.HashMap;
// w  w  w  . j  a  v  a2  s  . c o  m
public class Main {

  public static void main(String[] args) {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String test = "BUNANA";
    char[] chars = test.toCharArray();

    for (int i = 0; i < chars.length; i++) {
      if (!map.containsKey(chars[i])) {
        map.put(chars[i], 1);
      }
      map.put(chars[i], map.get(chars[i]) + 1);
    }

    System.out.println(map.toString());
  }

}