The following program is printing null
. I am not able to understand why.
public class ConcurrentHashMapTest { public static final ConcurrentMap<String, String> map = new ConcurrentHashMap<>(5, 0.9f, 2); public static void main(String[] args) { map.putIfAbsent("key 1", "value 1"); map.putIfAbsent("key 2", "value 2"); String value = get("key 3"); System.out.println("value for key 3 --> " + value); } private static String get(final String key) { return map.putIfAbsent(key, "value 3"); } }
Could someone help me understand the behavior?
The putIfAbsent(Key, value) method of Hashtable class which allows to map a value to a given key if given key is not associated with a value or mapped to null. A null value is returned if such key-value set is already present in the HashMap.
The Java HashMap putIfAbsent() method inserts the specified key/value mapping to the hashmap if the specified key is already not present in the hashmap. The syntax of the putIfAbsent() method is: hashmap.putIfAbsent(K key, V value) Here, hashmap is an object of the HashMap class.
computeIfAbsent returns "the current (existing or computed) value associated with the specified key, or null if the computed value is null". putIfAbsent returns "the previous value associated with the specified key, or null if there was no mapping for the key".
Problem is that by definition putIfAbsent return old value and not new value (old value for absent is always null). Use computeIfAbsent - this will return new value for you.
private static String get(final String key) { return map.computeIfAbsent(key, s -> "value 3"); }
ConcurrentMap.putIfAbsent
returns the previous value associated with the specified key, or null if there was no mapping for the key. You did not have a value associated with "key 3". All correct.
NOTE: Not just for ConcurrentMap
, this applies to all implementations of Map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With