当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java HashMap putIfAbsent(key, value)用法及代码示例


仅当此HashMap实例中不存在这样的映射时,才使用HashMap类的putIfAbsent(K key,V value)方法来映射具有指定值的指定键。

用法:

public V putIfAbsent(K key, V value)

参数:此方法接受两个参数:


  • key:这是必须映射提供的值的键。
  • value:如果不存在,则为必须与提供的键相关联的值。

返回值:此方法返回null(如果之前没有与提供的键的映射,或者已映射为null值)或与提供的键关联的先前值。

异常:此方法引发以下异常:

  • NullPointerException :如果指定的键或值为null,并且此映射不支持空值。
  • IllegalArgumentException:如果指定的键或值阻止其存储在Map中。

程序1:

// Java program to demonstrate 
// putIfAbsent(Key, value) method. 
  
import java.util.*; 
  
public class GFG { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  
        // create a HashMap and add some values 
        HashMap<String, Integer> map 
            = new HashMap<>(); 
        map.put("a", 10000); 
        map.put("b", 55000); 
        map.put("c", 44300); 
        map.put("e", 53200); 
  
        // print original map 
        System.out.println("HashMap:\n "
                           + map.toString()); 
  
        // put a new value which is not mapped 
        // before in map 
        map.putIfAbsent("d", 77633); 
  
        // print newly mapped map 
        System.out.println("New HashMap:\n "
                           + map); 
    } 
}
输出:
HashMap:
 {a=10000, b=55000, c=44300, e=53200}
New HashMap:
 {a=10000, b=55000, c=44300, d=77633, e=53200}

程序2:

// Java program to demonstrate 
// putIfAbsent(Key, value) method. 
  
import java.util.*; 
  
public class GFG { 
  
    // Main method 
    public static void main(String[] args) 
    { 
  
        // create a HashMap and add some values 
        HashMap<String, Integer> map 
            = new HashMap<>(); 
        map.put("a", 10000); 
        map.put("b", 55000); 
        map.put("c", 44300); 
        map.put("e", null); 
  
        // print original map 
        System.out.println("HashMap:\n "
                           + map.toString()); 
  
        // put a new value which is not mapped 
        // before in map and store the returned 
        // value in r1 
        Integer r1 = map.putIfAbsent("d", 77633); 
  
        // put a new value for key 'e' which is mapped 
        // with a null value, and store the returned 
        // value in r2 
        Integer r2 = map.putIfAbsent("e", 77633); 
  
        // print the value of r1 
        System.out.println("Value of r1:\n " + r1); 
  
        // print the value of r2 
        System.out.println("Value of r2:\n " + r2); 
  
        // print newly mapped map 
        System.out.println("New HashMap:\n "
                           + map); 
    } 
}
输出:
HashMap:
 {a=10000, b=55000, c=44300, e=null}
Value of r1:
 null
Value of r2:
 null
New HashMap:
 {a=10000, b=55000, c=44300, d=77633, e=77633}

参考:https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#putIfAbsent-K-V-



相关用法


注:本文由纯净天空筛选整理自ankit0812大神的英文原创作品 HashMap putIfAbsent(key, value) method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。