Java8 Map中新增的方法使用總結

前言

得益於 Java 8 的 default 方法特性,Java 8 對 Map 增加了不少實用的默認方法,像 getOrDefault, forEach, replace, replaceAll, putIfAbsent, remove(key, value), computeIfPresent, computeIfAbsent, compute 和merge 方法。另外與 Map 相關的 Map.Entry 也新加了多個版本的 comparingByKey 和 comparingByValue 方法。

爲達到熟練運用上述除 getOrDefault 和 forEach 外的其他方法,有必要逐一體驗一番,如何調用,返回值以及調用後的效果如何。看看每個方法不至於 Java 8 那麼多年還總是  if(map.containsKey(key))... 那樣的老套操作。

前注:Map 新增方法對  present 的判斷是 map.containsKey(key) && map.get(key) != null,簡單就是  map.get(key) != null,也就是即使 key 存在,但對應的值爲 null 的話也視爲 absent。absent 就是 map.get(key) == null。

不同 Map 實現對 key/value 是否能爲 null 有不同的約束, HashMap, LinkedHashMap, key 和 value 都可以爲 null 值,TreeMap 的 key 爲不能爲 null, 但 value 可以爲 null, 而 Hashtable, ConcurrentMap 則 key 和 value 都不同爲 null。一句話 absent/present 的判斷是 map.get(key) 是否爲 null。

方法介紹的順序是它們相對於本人的生疏程度而定的。每個方法介紹主要分兩部分,參考實現代碼與示例代碼執行效果。參考實現代碼摘自 JDK 官方的 Map JavaDoc。

putIfAbsent 方法

方法原型 V putIfAbsent(K key, V value) ,  如果 key 不存在或相關聯的值爲 null, 則設置新的 key/value 值。

參考實現:

V v = get(key);
if (v == null) {
v = put(key, value);
}
return v;

如果原 map 中對應 key 的值爲爲 null 返回舊值,或者返回新的 value 值

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.putIfAbsent("a", "aaa"); //ret 爲"aaa", map 爲 {"a":"aaa"}
ret = map.putIfAbsent("a", "bbb"); //ret 爲 "aaa", map 還是 {"a":"aaa"}

map.put("b", null);
ret = map.putIfAbsent("b", "bbb"); //ret 爲 "bbb", map 爲 {"a":"aaa","b":"bbb"}

computeIfPresent 方法

方法原型 V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction),如果指定的 key 存在並且相關聯的 value 不爲 null 時,根據舊的 key 和 value 計算 newValue 替換舊值,newValue 爲 null 則從 map 中刪除該 key; key 不存在或相應的值爲 null 時則什麼也不做,方法的返回值爲最終的 map.get(key)。

參考實現:

if (map.get(key) != null) {
V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (newValue != null)
map.put(key, newValue);
else
map.remove(key);
}

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 爲 {}
map.put("a", null); //map 爲 ["a":null]
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret null, map 爲 {"a":null}
map.put("a", "+aaa");
ret = map.computeIfPresent("a", (key, value) -> key + value); //ret "a+aaa", map 爲 {"a":"a+aaa"}
ret = map.computeIfPresent("a", (key, value) -> null); //ret 爲 null, map 爲 {},計算出的 null 把 key 刪除了

計算出的值爲 null 時直接刪除 key 而不是設置對應 key 的值爲 null, 這能照顧到值不能爲 null 的 Map 實現,如 Hashtable 和 ConcurrentMap。

computeIfAbsent 方法

方法原型 V computeIfAbsent(K key, Function<? super <, ? extends V> mappingFunction), 與上一個方法相反,如果指定的 key 不存在或相關的 value 爲 null 時,設置 key 與關聯一個計算出的非 null 值,計算出的值爲 null 的話什麼也不做(不會去刪除相應的  key)。如果 key 存在並且對應 value 爲 null 的話什麼也不做。同樣,方法的返回值也是最終的 map.get(key)。

參考實現:

if (map.get(key) == null) {
V newValue = mappingFunction.apply(key);
if (newValue != null)
map.put(key, newValue);
}

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.computeIfAbsent("a", key -> key + "123"); //ret "a123", map 爲 {"a":"a123"}
ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a123", map 爲 {"a":"a123"}
map.put("a", null);
ret = map.computeIfAbsent("a", key -> key + "456"); //ret "a456", map 爲 {"a":"a456"}
ret = map.computeIfAbsent("a", key -> null); //ret 爲 "a456", map 爲 {"a":"a456"}

replace(K key, V value) 方法

只要 key 存在,不管對應值是否爲  null,則用傳入的 value 替代原來的值。即使傳入的 value 是 null 也會用來替代原來的值,而不是刪除,注意這對於 value 不能爲  null 值的  Map  實現將會造成 NullPointerException。key 不存在不會修改 Map 的內容,返回值總是原始的 map.get(key) 值。

參考實現:

if (map.containsKey(key)) {
return map.put(key, value);
} else
return null;

示例及效果:

String ret;
Map<String, String> map = new HashMap<>();
ret = map.replace("a", "abc"); //ret 爲 null,map 爲 {}
map.put("a", "ddd");
ret = map.replace("a", "abc"); //ret 爲 "ddd", map 爲 {"a":"abc"}
ret = map.replace("a", null); //ret 爲 "abc", map 爲 {"a":null}
ret = map.replace("a", "ddd"); //ret 爲 null, map 爲 {"a":"ddd"}

replace(K key, V oldValue, V newValue)

當且僅當 key 存在,並且對應值與 oldValue 不相等,才用 newValue 作爲 key 的新相關聯值,返回值爲是否進行了替換。

參考實現:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.put(key, newValue);
return true;
} else
return false;

示例及效果:

boolean ret;
Map<String, String> map = new HashMap<>() ;
ret = map.replace("a", null, "aaa"); //ret 爲 false, map 爲 {}
map.put("a", null);
ret = map.replace("a", null, "aaa"); //ret 爲 true, map 爲 {"a":"aaa"}
ret = map.replace("a", "aaa", null); //ret 爲 true, map 爲 {"a":null}
ret = map.replace("a", "aaa", "bbb");//ret 爲 false, map 爲 {"a":null}

replaceAll 方法

方法原型 void replaceAll(BiFunction<? super K, ? super V, ? extends V> function)。它更像一個傳統函數型語言的 map 函數,即對於 Map 中的每一個元素應用函數 function, 輸入爲 key 和  value。

參考實現:

for (Map.Entry<K, V> entry : map.entrySet())
entry.setValue(function.apply(entry.getKey(), entry.getValue()));

示例及效果:

Map<String, String> map = new HashMap<>() ;
map.put("a", "aaa");
map.put("b", "bbb"); //map 爲 {"a":"aaa","b":"bbb"}
map.replaceAll((key, value) -> key + "-" + value); //map 爲 {"a":"a-aaa","b":"b-bbb"}

remove(key, value)

這個也不用多說,key 與 value 都匹配時才刪除。

參考實現:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;

compute 方法

方法原型 V compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction), 它是 computeIfAbsent 與 computeIfPresent  的結合體。也就是既不管 key 存不存在,也不管 key 對應的值是否爲 null, compute 死活都要設置與 key 相關聯的值,或者計算出的值爲 null 時刪除相應的 key, 返回值爲最終的 map.get(key)。

參考實現:

V oldValue = map.get(key);
V newValue = remappingFunction.apply(key, oldValue);
if (oldValue != null ) {
if (newValue != null)
map.put(key, newValue);
else
map.remove(key);
} else {
if (newValue != null)
map.put(key, newValue);
else
return null;
}

示例及效果:

String ret;
Map<String, String> map = new HashMap<>() ;
ret = map.compute("a", (key, value) -> "a" + value); //ret="anull", map={"a":"anull"}
ret = map.compute("a", (key, value) -> "a" + value); //ret="aanull", map={"a":"aanull"}
ret = map.compute("a", (key, value) -> null); //ret=null, map={}

merge 方法

方法原型 V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFucntion),這是至今來說比較神祕的一個方法,尚未使用到它。如果指定的 key 不存在,或相應的值爲 null 時,則設置  value 爲相關聯的值。否則根據 key 對應的舊值和 value 計算出新的值 newValue,newValue 爲 null 時,刪除該key, 否則設置 key 對應的值爲  newValue。方法的返回值也是最終的  map.get(key) 值。

參考實現:

V oldValue = map.get(key);
V newValue = (oldValue == null) ? value :
remappingFunction.apply(oldValue, value);
if (newValue == null)
map.remove(key);
else
map.put(key, newValue);

注意 value 不能爲 null 值

示例及效果:

String ret;
Map<String, String> map = new HashMap<>() ;
ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
ret = map.merge("a", "bb", (oldValue, value) -> oldValue + "-" + value); //ret="aa-bb", map={"a":"aa-bb"}
ret = map.merge("a", "bb", (oldValue, value) -> null); //ret=null, map={}
map.put("a", null);
ret = map.merge("a", "aa", (oldValue, value) -> oldValue + "-" + value); //ret="aa", map={"a":"aa"}
map.put("a", null);
ret = map.merge("a", "bb", (oldValue, value) -> null); //ret="bb", map={"a":"bb"}
ret = map.merge("a", null, (oldValue, value) -> oldValue + "-" + value); //NullPointerException, value 不能爲 null

Map.Entry comparingByKey 和  comparingByValue 方法

另外介紹一下 Map.Entry 新加的兩個排序方法,它們分別有無參與帶 Comparator 參數可嵌套使用的兩個版本。comparingByKey(), comparingByKey(Comparator<? super K> cmp), comparingByValue() 和 comparingByValue(Comparator<? super V> cmp)。

示例代碼如下:

map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
map.entrySet().stream().sorted(Map.Entry.comparingByKey(String::compareTo)).collect(Collectors.toList());
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
map.entrySet().stream().sorted(Map.Entry.comparingByValue(String::compareTo)).collect(Collectors.toList());

 

您可能感興趣的文章:

文章同步發佈: https://www.geek-share.com/detail/2755357127.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章