僅當此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-
相關用法
- Java HashMap computeIfAbsent()用法及代碼示例
- Java HashMap replace(key, value)用法及代碼示例
- Java HashMap compute()用法及代碼示例
- Java HashMap getOrDefault(key, defaultValue)用法及代碼示例
- Java HashMap merge(key, value, BiFunction)用法及代碼示例
- Java HashMap computeIfPresent(key, BiFunction)用法及代碼示例
- Java HashMap replaceAll(BiFunction)用法及代碼示例
- Java HashMap forEach(BiConsumer)用法及代碼示例
- Java HashMap replace(key, oldValue, newValue)用法及代碼示例
- Java HashMap get()用法及代碼示例
- Java HashMap put()用法及代碼示例
- Java HashMap putAll()用法及代碼示例
注:本文由純淨天空篩選整理自ankit0812大神的英文原創作品 HashMap putIfAbsent(key, value) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。