📜  Java中的 ConcurrentHashMap putIfAbsent() 方法

📅  最后修改于: 2022-05-13 01:54:38.231000             🧑  作者: Mango

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 chm = 
                     new ConcurrentHashMap();
  
        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 chm = 
                          new ConcurrentHashMap();
  
        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: Java/util/concurrent/ConcurrentHashMap.html#putIfAbsent()