Counting occurrences of a key in a Map in Java(在 Java 中计算 Map 中键的出现次数)
问题描述
我正在编写一个项目,该项目从 .java 文件中捕获 Java 关键字并使用地图跟踪出现的情况.我过去曾成功使用过类似的方法,但我似乎无法将这种方法用于我的预期用途.
I'm writing a project that captures Java keywords from a .java file and keeps track of the occurrences with a map. I've used a similar method in the past successfully, but I can't seem to adopt this method for my intended use here.
Map<String,Integer> map = new TreeMap<String,Integer>();
Set<String> keywordSet = new HashSet<String>(Arrays.asList(keywords));
Scanner input = new Scanner(file);
int counter = 0;
while (input.hasNext())
{
String key = input.next();
if (key.length() > 0)
{
if (keywordSet.contains(key))
{
map.put(key, 1);
counter++;
}
if(map.containsKey(key)) <--tried inner loop here, failed
{
int value = map.get(key);
value++;
map.put(key, value);
}
}
该代码块应该将关键字添加到键中,并在每次出现相同键时递增值.到目前为止,它添加了关键字,但未能正确增加值.这是一个示例输出:
This block of code is supposed to add the keyword to the key, and increment the value each time the same key occurs. So far, it adds the keywords, but fails to properly increment the value. here is a sample output:
{assert=2, class=2, continue=2, default=2, else=2, ...}
基本上,它会增加地图中的每个值,而不是它应该增加的值.我不确定我是在想这个还是什么.我尝试了一个内部循环,它给了我疯狂的结果.我真的希望我只是想多了.非常感谢任何帮助!
Basically it increments every value in the map instead of the ones it's supposed to. I'm not sure if I'm over-thinking this or what. I've tried an inner loop and it gave me insane results. I really hope I'm just over-thinking this. Any help is greatly appreciated!
推荐答案
对于您扫描的每个键,您都会在映射中创建一个新条目(覆盖现有条目).然后,下一个条件成立,因此您将计数加 1,达到值 2.
For every key you scan you create a new entry in the map (overriding the existing one). Then, the next condition holds so you increment the count by 1, reaching the value 2.
内部应该是这样的:
if (keywordSet.contains(key))
{
Integer value = map.get(key);
if (value == null)
value = 0;
value++;
map.put(key, value);
}
无论如何,请考虑使用某种可变整数来提高效率.您不必覆盖地图中的条目,也不会执行过多的整数装箱操作.
Anyway, consider using some kind of a mutable integer to make this more efficient. You won't have to override entries in the map, and you won't be doing too much Integer boxing operations.
这篇关于在 Java 中计算 Map 中键的出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中计算 Map 中键的出现次数


- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01