You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Map未初始化赋值及Java 11合并操作实现问询

回答

Yep, your memory serves you right—though technically this concise one-liner has been possible since Java 8, Java 11 fully supports this streamlined approach too!

Your original code splits the logic into two steps: first ensuring the key has an initialized AtomicInteger via putIfAbsent, then fetching the value to increment it. You can merge these into a single line using ConcurrentHashMap's computeIfAbsent method. This method atomically checks for the key's existence: if it's missing, it runs your initialization logic, then returns either the existing or newly created value—letting you chain the increment call directly.

Here's the simplified code:

private final Map<String, AtomicInteger> map = new ConcurrentHashMap<>();

public void increaseValue(String key) {
    map.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet();
}

For even more brevity, you can replace the lambda with a method reference (since AtomicInteger's no-arg constructor initializes to 0, which matches your original logic perfectly):

map.computeIfAbsent(key, AtomicInteger::new).incrementAndGet();

Just like your original implementation, this approach is thread-safe for concurrent access—computeIfAbsent is an atomic operation in ConcurrentHashMap, so you won't run into race conditions where multiple threads try to initialize the same key at once.

内容的提问来源于stack exchange,提问作者Vitalii

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 18:32:51