不管存不存在key,都設值:
1. put
put傳回舊值,如果沒有則傳回null
@Test
public void testMap() {
Map<String, String> map = new HashMap<>();
map.put("a","A");
map.put("b","B");
String v = map.put("b","v"); // 輸出 B
System.out.println(v);
String v1 = map.put("c","v");
System.out.println(v1); // 輸出:NULL
}
1
2
3
4
5
6
7
8
9
10
2. compute(相當于put,隻不過傳回的是新值)
compute:傳回新值
當key不存在時,執行value計算方法,計算value
map.put("a", "A");
map.put("b", "B");
String val = map.compute("b", (k, v) -> "v"); // 輸出 v
System.out.println(val);
String v1 = map.compute("c", (k, v) -> "v"); // 輸出 v
System.out.println(v1);
11
12
以下幾個方法,如果不存在,再put:
1. putIfAbsent
putIfAbsent傳回舊值,如果沒有則傳回null
先計算value,再判斷key是否存在
String v = map.putIfAbsent("b","v"); // 輸出 B
String v1 = map.putIfAbsent("c","v"); // 輸出 null
2. computeIfAbsent
computeIfAbsent:存在時傳回存在的值,不存在時傳回新值
參數為:key,value計算方法
String v = map.computeIfAbsent("b",k->"v"); // 輸出 B
String v1 = map.computeIfAbsent("c",k->"v"); // 輸出 v
————————————————
版權聲明:本文為CSDN部落客「衣冠の禽獸」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/wang_8101/article/details/82191146