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 中键的出现次数


基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01