1

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?

Vitalii
  • 10,091
  • 18
  • 83
  • 151

1 Answers1

6

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

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
ernest_k
  • 44,416
  • 5
  • 53
  • 99