未初始化时在java map中初始化一个值

Vit*_*lii 1 java concurrenthashmap java-11

我有一张地图,通过调用increaseValue方法我需要增加它的价值。在该方法中,我检查值是否存在,如果不存在,则对其进行初始化并增加它。

private final Map<String, AtomicInteger> map = new ConcurrentHashMap<>();
 
public void increaseValue(String key) {
    map.putIfAbsent(key, new AtomicInteger(0));
    map.get(key).incrementAndGet();
}
Run Code Online (Sandbox Code Playgroud)

据我记得在java 11中这两个操作可以在一行中完成,不是吗?

ern*_*t_k 6

即使在 Java 8 中,它仍然是可能的。突出使用computeIfAbsent()

map.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet();
Run Code Online (Sandbox Code Playgroud)

根据javadocs computeIfAbsent

返回: 与指定键关联的当前(现有的或计算出的)值,如果计算出的值为空,则返回空值