Java ConcurrentHashMap putIfAbsent()方法
java.util.concurrent.ConcurrentHashMap.putIfAbsent() 是Java中的一个内置函数,它接受一个键和一个值作为参数,如果指定的键没有映射到任何值,就会映射它们。
语法
chm.putIfAbsent(key_elem, val_elem)
参数: 该函数接受两个参数,描述如下。
- key_elem: 如果key_elem没有与任何值相关联,这个参数指定指定的val_elem所要映射的键。
- val_elem: 这个参数指定要映射到指定key_elem的值 。
返回值: 该函数返回映射到键的现有值,如果之前没有值映射到键,则返回null。
异常: 当指定的参数为空时,该函数抛出NullPointerException。
下面的程序说明了ConcurrentHashMap.putIfAbsent()方法。
程序1: 一个现有的键被作为参数传递给函数。
// Java Program Demonstrate putIfAbsent()
// method of ConcurrentHashMap
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap<Integer, String> chm =
new ConcurrentHashMap<Integer, String>();
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Gfg");
chm.put(104, "GFG");
// Displaying the HashMap
System.out.println("Initial Mappings are: "
+ chm);
// Inserting non-existing key along with value
String returned_value = (String)chm.putIfAbsent(108, "All");
// Verifying the returned value
System.out.println("Returned value is: "
+ returned_value);
// Displayin the new map
System.out.println("New mappings are: "
+ chm);
}
}
输出。
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
Returned value is: null
New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG, 108=All}
程序2: 一个不存在的键被作为参数传给函数。
// Java Program Demonstrate putIfAbsent()
// method of ConcurrentHashMap
import java.util.concurrent.*;
class ConcurrentHashMapDemo {
public static void main(String[] args)
{
ConcurrentHashMap<Integer, String> chm =
new ConcurrentHashMap<Integer, String>();
chm.put(100, "Geeks");
chm.put(101, "for");
chm.put(102, "Geeks");
chm.put(103, "Gfg");
chm.put(104, "GFG");
// Displaying the HashMap
System.out.println("Initial Mappings are: "
+ chm);
// Inserting existing key along with value
String returned_value = (String)chm.putIfAbsent(100, "All");
// Verifying the returned value
System.out.println("Returned value is: "
+ returned_value);
// Displayin the new map
System.out.println("New mappings are: "
+ chm);
}
}
输出。
Initial Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
Returned value is: Geeks
New mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Gfg, 104=GFG}
参考资料 : https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html#putIfAbsent()
极客教程