Search code examples
javalistloopsdictionarytreemap

TreeMap -- How to find the number of words that begin with each letter of the alphabet


So I have a list of words. For example, {Apple, Available, Art, Between, Beyond, Door, Drive, ......}

and I want to show the number of words that begin with each letter of the alphabet, so the outcome should be like A = 3, B = 2, D = 2, ......

Here is the code I wrote, but apparently it didn't work like the way I wanted.

    Map<String, Integer> myMap = new TreeMap<String, Integer>();

    for (int i = 0; i < theWords.length; i++) {
        for (char alphabet = 'A'; alphabet <= 'Z'; alphabet++) {
            int numOfWords = 0;
            char firstLetter = theWords[i].charAt(0);
            if (firstLetter == alphabet) {
                myMap.put(String.valueOf(alphabet), numOfWords + 1);
            }
        }   
    }
    System.out.println(myMap);

And this is the outcome I got ...

{A=1, B=1, C=1, D=1, E=1, F=1, G=1, H=1, J=1, K=1, L=1, M=1, N=1, O=1, P=1, Q=1, R=1, S=1, T=1, U=1, W=1, Y=1}

P.S. I have to use TreeMap.


Solution

  • Rather than the double loop, you can get the first character and add to the Map.

    Something akin to:

    for (String fruit : theFruits) {
      String firstLetter = fruit.substring(0, 1);
      Integer count = myMap.get(firstLetter);
      if (count == null) {
        myMap.put(firstLetter, 1);
      }
      else {
        myMap.put(firstLetter, ++count);
      }
    }