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

