Suppose we have a HashMap<String, Integer> in Java.

How do I update (increment) the integer-value of the string-key for each existence of the string I find?

One could remove and reenter the pair, but overhead would be a concern.
Another way would be to just put the new pair and the old one would be replaced.

In the latter case, what happens if there is a hashcode collision with a new key I am trying to insert? The correct behavior for a hashtable would be to assign a different place for it, or make a list out of it in the current bucket.

推荐答案

map.put(key, map.get(key) + 1);

should be fine. It will update the value for the existing mapping. Note that this uses auto-boxing. With the help of map.get(key) we get the value of corresponding key, then you can update with your requirement. Here I am updating to increment value by 1.

Java相关问答推荐

try 使用Java 9或更高版本对特殊对象图进行解析时出现NullPointerException

S的字符串表示是双重精确的吗?

为什么使用JDK21获取锁定锁比使用JDK11慢

为什么S的文档中说常量方法句柄不能在类的常量池中表示?

将Spring Boot 3.2.0升级到3.2.1后查询执行错误

如何仅使用键/ID的一部分(组合)高效地返回映射值?

Java Telnet客户端重复的IAC符号

Instancio未在日志(log)中显示测试失败消息

在macOS上读取文件会导致FileNotFound,即使文件存在(并且具有权限)

在Ubuntu 23.10上使用mp3创建JavaFX MediaPlayer时出错

如何在Java中为thunk创建映射器函数

删除打印语句会影响功能...腐败在起作用?

使用@ExceptionHandler的GlobalExceptionHandler还是来自服务器的REST应答的ResponseEntity?

为什么我得到默认方法的值而不是被覆盖的方法的值?

Java中计算大n和k值模10^9+7的二项式系数的乘法公式输出错误值

如何显示新布局

Cucumber中第二个网页的类对象未初始化

如何组合Mono和Flux

对于 Hangman 游戏,索引 0 超出长度 0 的范围

为什么 Random() 的行为不符合预期?