欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java8 Map中新增的方法使用總結(jié)

 更新時(shí)間:2018年11月01日 10:43:28   作者:隔葉黃鶯  
這篇文章主要介紹了Java8 Map中新增的方法使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

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

為達(dá)到熟練運(yùn)用上述除 getOrDefault 和 forEach 外的其他方法,有必要逐一體驗(yàn)一番,如何調(diào)用,返回值以及調(diào)用后的效果如何。看看每個(gè)方法不至于 Java 8 那么多年還總是  if(map.containsKey(key))... 那樣的老套操作。

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

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

方法介紹的順序是它們相對(duì)于本人的生疏程度而定的。每個(gè)方法介紹主要分兩部分,參考實(shí)現(xiàn)代碼與示例代碼執(zhí)行效果。參考實(shí)現(xiàn)代碼摘自 JDK 官方的 Map JavaDoc。

putIfAbsent 方法

方法原型 V putIfAbsent(K key, V value) ,  如果 key 不存在或相關(guān)聯(lián)的值為 null, 則設(shè)置新的 key/value 值。

參考實(shí)現(xiàn):

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

如果原 map 中對(duì)應(yīng) 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 存在并且相關(guān)聯(lián)的 value 不為 null 時(shí),根據(jù)舊的 key 和 value 計(jì)算 newValue 替換舊值,newValue 為 null 則從 map 中刪除該 key; key 不存在或相應(yīng)的值為 null 時(shí)則什么也不做,方法的返回值為最終的 map.get(key)。

參考實(shí)現(xiàn):

 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 為 {},計(jì)算出的 null 把 key 刪除了

計(jì)算出的值為 null 時(shí)直接刪除 key 而不是設(shè)置對(duì)應(yīng) key 的值為 null, 這能照顧到值不能為 null 的 Map 實(shí)現(xiàn),如 Hashtable 和 ConcurrentMap。

computeIfAbsent 方法

方法原型 V computeIfAbsent(K key, Function<? super <, ? extends V> mappingFunction), 與上一個(gè)方法相反,如果指定的 key 不存在或相關(guān)的 value 為 null 時(shí),設(shè)置 key 與關(guān)聯(lián)一個(gè)計(jì)算出的非 null 值,計(jì)算出的值為 null 的話什么也不做(不會(huì)去刪除相應(yīng)的  key)。如果 key 存在并且對(duì)應(yīng) value 為 null 的話什么也不做。同樣,方法的返回值也是最終的 map.get(key)。

參考實(shí)現(xiàn):

 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 存在,不管對(duì)應(yīng)值是否為  null,則用傳入的 value 替代原來(lái)的值。即使傳入的 value 是 null 也會(huì)用來(lái)替代原來(lái)的值,而不是刪除,注意這對(duì)于 value 不能為  null 值的  Map  實(shí)現(xiàn)將會(huì)造成 NullPointerException。key 不存在不會(huì)修改 Map 的內(nèi)容,返回值總是原始的 map.get(key) 值。

參考實(shí)現(xiàn):

 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)

當(dāng)且僅當(dāng) key 存在,并且對(duì)應(yīng)值與 oldValue 不相等,才用 newValue 作為 key 的新相關(guān)聯(lián)值,返回值為是否進(jìn)行了替換。

參考實(shí)現(xiàn):

 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)。它更像一個(gè)傳統(tǒng)函數(shù)型語(yǔ)言的 map 函數(shù),即對(duì)于 Map 中的每一個(gè)元素應(yīng)用函數(shù) function, 輸入為 key 和  value。

參考實(shí)現(xiàn):

 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)

這個(gè)也不用多說(shuō),key 與 value 都匹配時(shí)才刪除。

參考實(shí)現(xiàn):

 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  的結(jié)合體。也就是既不管 key 存不存在,也不管 key 對(duì)應(yīng)的值是否為 null, compute 死活都要設(shè)置與 key 相關(guān)聯(lián)的值,或者計(jì)算出的值為 null 時(shí)刪除相應(yīng)的 key, 返回值為最終的 map.get(key)。

參考實(shí)現(xiàn):

 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),這是至今來(lái)說(shuō)比較神秘的一個(gè)方法,尚未使用到它。如果指定的 key 不存在,或相應(yīng)的值為 null 時(shí),則設(shè)置  value 為相關(guān)聯(lián)的值。否則根據(jù) key 對(duì)應(yīng)的舊值和 value 計(jì)算出新的值 newValue,newValue 為 null 時(shí),刪除該key, 否則設(shè)置 key 對(duì)應(yīng)的值為  newValue。方法的返回值也是最終的  map.get(key) 值。

參考實(shí)現(xiàn):

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 新加的兩個(gè)排序方法,它們分別有無(wú)參與帶 Comparator 參數(shù)可嵌套使用的兩個(gè)版本。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());

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

  • springboot 接收List 入?yún)⒌膸追N方法

    springboot 接收List 入?yún)⒌膸追N方法

    本文主要介紹了springboot 接收List 入?yún)⒌膸追N方法,本文主要介紹了7種方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-03-03
  • java 中遍歷取值異常(Hashtable Enumerator)解決辦法

    java 中遍歷取值異常(Hashtable Enumerator)解決辦法

    這篇文章主要介紹了java 中遍歷取值異常(Hashtable Enumerator)解決辦法的相關(guān)資料,用迭代器取值時(shí)拋出的異常:java.util.NoSuchElementException: Hashtable Enumerator ,需要的朋友可以參考下
    2017-08-08
  • SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例

    SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例

    這篇文章主要介紹了SpringBoot使用Redisson實(shí)現(xiàn)延遲執(zhí)行的完整示例,文中通過(guò)代碼示例講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-06-06
  • spring cglib 與 jdk 動(dòng)態(tài)代理

    spring cglib 與 jdk 動(dòng)態(tài)代理

    本篇文章主要介紹了spring cglib與jdk動(dòng)態(tài)代理的相關(guān)知識(shí),具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧
    2017-05-05
  • Springboot整合RabbitMq測(cè)試TTL的方法詳解

    Springboot整合RabbitMq測(cè)試TTL的方法詳解

    這篇文章主要介紹了Springboot整合RabbitMq測(cè)試TTL的設(shè)置,設(shè)置TTL一般由兩種設(shè)置方法,設(shè)置整個(gè)隊(duì)列的過(guò)期時(shí)間另一種設(shè)置單個(gè)消息的過(guò)期時(shí)間,通過(guò)示例圖文相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下
    2022-03-03
  • 聊聊Java并發(fā)中的Synchronized

    聊聊Java并發(fā)中的Synchronized

    這篇文章主要介紹了聊聊Java并發(fā)中的Synchronized,介紹了同步的基礎(chǔ),原理,鎖的相關(guān)內(nèi)容,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11
  • JAVA發(fā)送http get/post請(qǐng)求,調(diào)用http接口、方法詳解

    JAVA發(fā)送http get/post請(qǐng)求,調(diào)用http接口、方法詳解

    這篇文章主要介紹了Java發(fā)送http get/post請(qǐng)求調(diào)用接口/方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • 詳解Spring?Security怎么從數(shù)據(jù)庫(kù)加載我們的用戶

    詳解Spring?Security怎么從數(shù)據(jù)庫(kù)加載我們的用戶

    這篇文章主要為大家介紹了Spring?Security怎么從數(shù)據(jù)庫(kù)加載我們的用戶示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-01-01
  • java反射的作用知識(shí)點(diǎn)總結(jié)

    java反射的作用知識(shí)點(diǎn)總結(jié)

    在本篇文章里小編給大家整理的是關(guān)于java反射的作用知識(shí)點(diǎn)總結(jié),需要的朋友們可以學(xué)習(xí)下。
    2020-02-02
  • Spring?Boot集成validation實(shí)現(xiàn)參數(shù)校驗(yàn)功能

    Spring?Boot集成validation實(shí)現(xiàn)參數(shù)校驗(yàn)功能

    Bean?Validation?是一個(gè)運(yùn)行時(shí)的數(shù)據(jù)驗(yàn)證框架,在驗(yàn)證之后驗(yàn)證的錯(cuò)誤信息會(huì)被馬上返回,這篇文章主要介紹了Spring?Boot集成validation實(shí)現(xiàn)參數(shù)校驗(yàn)功能,需要的朋友可以參考下
    2024-05-05

最新評(píng)論