首页 > 解决方案 > TreeMap - 如何找到以字母表中每个字母开头的单词数

问题描述

所以我有一个单词列表。例如,{Apple、Available、Art、Between、Beyond、Door、Drive、......}

我想显示以字母表中每个字母开头的单词数,所以结果应该是 A = 3, B = 2, D = 2, ......

这是我编写的代码,但显然它不像我想要的那样工作。

    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);

这就是我得到的结果......

{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}

PS我必须使用TreeMap。

标签: javalistloopsdictionarytreemap

解决方案


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);
  }
}

推荐阅读