Search code examples
javajava-11concurrenthashmap

Init a value in java map when not initialized


I have a map and by calling increaseValue method I need to increase it's value. In the method I check if value exists, if not I initialize it and that I increase it.

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

As far as I remember in java 11 these two operations can be done in one line, can't them?


Solution

  • Even in Java 8, it's still possible. Jut use computeIfAbsent():

    map.computeIfAbsent(key, k -> new AtomicInteger(0)).incrementAndGet();
    

    According to the javadocs of computeIfAbsent

    Returns: the current (existing or computed) value associated with the specified key, or null if the computed value is null