java - 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。
解决方案
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);
}
}
推荐阅读
- redis - Redis 反向模式匹配
- ios - UIPageViewController Delegate 方法仅在第一次调用
- python - 如何从我的 python 代码创建独立程序(在 linux 上)?
- html - 当我在 blazor 中选择一个选项时如何执行代码
- javascript - Gatsby GraphQL 自定义日期格式字符串
- c# - 如何使用 C# iTextSharp 检测 PDF 中的矩形和框
- javascript - Woocommerce:如何将产品从 iframe 添加到购物车?
- java - 只有在重构包名称之后,才考虑在您的配置中定义一个 * 类型的 bean
- c# - VS2019 C# OleDB 在路径中使用“AppDomain.CurrentDomain.BaseDirectory”导致VS安装目录而不是项目目录
- google-docs - 如何将当前文件的位置插入googl docs?