public V putIfAbsent(K key, V value)
|
What do putIfAbsent method do>
If map does not contain specified key, put specified key-value pair in map and return null.
If map already contains specified key, return value corresponding to specified key.
putIfAbsent method is equivalent to writing following code >
synchronized (map){
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
}
|
Program to create method that provides functionality similar to putIfAbsent method of ConcurrentHashMap and to be used with HashMap >
import java.util.HashMap;
import java.util.Map;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class HashMapTest {
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String args[]) {
map.put(1, "javaMadeSoEasy");
System.out.println("hashMap : "+map);
System.out.println("\n functionalityOfPutIfAbsent method >> "+
functionalityOfPutIfAbsent(1, "ankit"));
System.out.println("hashMap : "+map);
System.out.println("\n functionalityOfPutIfAbsent method >> "+
functionalityOfPutIfAbsent(2, "audi"));
System.out.println("hashMap : "+map);
}
/**
* Method is created to be used with HashMap, And
* method provides functionality similar to putIfAbsent
* method of ConcurrentHashMap.
*/
public static synchronized String functionalityOfPutIfAbsent(Integer key,String value){
if (!map.containsKey(key))
return map.put(key, value);
else
return map.get(key);
}
}
/*OUTPUT
hashMap : {1=javaMadeSoEasy}
functionalityOfPutIfAbsent method >> javaMadeSoEasy
hashMap : {1=javaMadeSoEasy}
functionalityOfPutIfAbsent method >> null
hashMap : {1=javaMadeSoEasy, 2=audi}
*/
|
Please note functionalityOfPutIfAbsent method is synchronized, because this method provides same functionality as that of ConcurrentHashMap’s putIfAbsent method and all methods in ConcurrentHashMap are synchronized.
functionalityOfPutIfAbsent(1, "ankit") > returned javaMadeSoEasy because map was already having that key.
functionalityOfPutIfAbsent(2, "audi") > putted specified key-value pair in map and returned null because map wasn’t having that key.
RELATED LINKS>