0

I have a code written to count the number of times something occurs.... but how do i ( keeping what i have) make another method that counts them based on their occurrences?

like "holy now brown cow"

o 4
w 4
n 2
b 1
c 1
h 1

as well as what it already does

( The String is: how now brown cow Number of ' ' is 3 Number of 'b' is 1 Number of 'c' is 1 Number of 'h' is 1 Number of 'n' is 2 Number of 'o' is 4 Number of 'r' is 1 Number of 'w' is 4)

my code:

public static void main(String[] args) {

    String str = "how now brown cow";

    char[] char_array = str.toCharArray();

    System.out.println("The String is: " + str);

    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("Number of '" + key + "' is  "+ charCounter.get(key));
    }

}
Susan
  • 1
  • 2
  • i want it to do both what it does now ( The String is: how now brown cow Number of ' ' is 3 Number of 'b' is 1 Number of 'c' is 1 Number of 'h' is 1 Number of 'n' is 2 Number of 'o' is 4 Number of 'r' is 1 Number of 'w' is 4) – Susan Jun 29 '15 at 23:53
  • `HashMap`s are unsorted. – Matt Ball Jun 29 '15 at 23:54

0 Answers0