Issue
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
Answered By - ernest_k
Answer Checked By - David Marino (JavaFixing Volunteer)