Java Data Type How to - Get Occurences of a letter in a phrase








Question

We would like to know how to get Occurences of a letter in a phrase.

Answer

import java.util.HashMap;
/*from  www  .j a va2  s .  co m*/
public class Main {
  public static HashMap tallyPrint(String phrase) {
    int count = 0;
    HashMap<Character, Integer> fav = new HashMap<Character, Integer>();
    for (int i = 0; i < phrase.length(); i++) {
      if (fav.containsKey(phrase.charAt(i)))
        fav.put(phrase.charAt(i), (fav.get(phrase.charAt(i))) + 1);
      else
        fav.put(phrase.charAt(i), 1);
    }
    return fav;
  }

  public static void main(String[] args) {
    System.out.println(tallyPrint("this is a test this "));
  }
}