Java Collection How to - Count the occurences of each character in a String with Hashmap








Question

We would like to know how to count the occurences of each character in a String with Hashmap.

Answer

import java.util.Map;
import java.util.TreeMap;
//from  w w w .  j a  v a 2 s .co m
public class Main {
  public static void main(String[] args) {
    String str = "this is a test";
    char[] char_array = str.toCharArray();

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();
    for (char i : char_array) {
      charCounter.put(i, charCounter.get(i) == null ? 1
          : charCounter.get(i) + 1);
    }
    for (Character key : charCounter.keySet()) {
      System.out.println("occurrence of '" + key + "' is  "
          + charCounter.get(key));
    }
  }
}

The code above generates the following result.