Junior — Middle
What are the differences between the put() and compute() methods in Java's ConcurrentHashMap class?
sobes.tech AI
Answer from AI
The put() and compute() methods in ConcurrentHashMap serve different purposes:
-
put(K key, V value)— simply adds or replaces the value for a key. If the key exists, the old value is replaced. -
compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)— a more flexible method that allows computing a new value based on the current one. The function receives the key and current value (ornullif absent), and returns the new value to be stored. If the function returnsnull, the key is removed.
Example of using compute():
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("apple", 2);
// Increment value for key "apple" by 1
map.compute("apple", (key, val) -> val == null ? 1 : val + 1);
// Set value to 1 if key is absent
map.compute("banana", (key, val) -> val == null ? 1 : val + 1);
Thus, compute() is useful for atomic updates based on the current value, while put() simply replaces the value.