Java 8 Map 新增方法詳解

Java 8 Map 新增方法詳解

1. getOrDefault

源碼

	 default V getOrDefault(Object key, V defaultValue) {V v;return (((v = get(key)) != null) || containsKey(key))? v: defaultValue;}

作用:安全獲取值,若key不存在則返回默認值
示例

Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 90);
System.out.println(scores.getOrDefault("Bob", 0)); // 輸出 0
2. forEach

源碼

    default void forEach(BiConsumer<? super K, ? super V> action) {Objects.requireNonNull(action);for (Map.Entry<K, V> entry : entrySet()) {K k;V v;try {k = entry.getKey();v = entry.getValue();} catch (IllegalStateException ise) {// this usually means the entry is no longer in the map.throw new ConcurrentModificationException(ise);}action.accept(k, v);}}

作用:遍歷Map的所有鍵值對
示例

Map<String, Integer> map = Map.of("A", 1, "B", 2);
map.forEach((k, v) -> System.out.println(k + ":" + v));
// 輸出:
// A:1
// B:2
3. replaceAll

源碼

    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {Objects.requireNonNull(function);for (Map.Entry<K, V> entry : entrySet()) {K k;V v;try {k = entry.getKey();v = entry.getValue();} catch (IllegalStateException ise) {// this usually means the entry is no longer in the map.throw new ConcurrentModificationException(ise);}// ise thrown from function is not a cme.v = function.apply(k, v);try {entry.setValue(v);} catch (IllegalStateException ise) {// this usually means the entry is no longer in the map.throw new ConcurrentModificationException(ise);}}}

作用:替換所有值(基于鍵值對的函數計算)
示例

Map<String, Integer> map = new HashMap<>();
map.put("A", 1); map.put("B", 2);
map.replaceAll((k, v) -> v * 10);
System.out.println(map); // 輸出 {A=10, B=20}
4. putIfAbsent

源碼

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

作用:僅當key不存在時插入值
示例

Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.putIfAbsent("A", 100); // 無效
map.putIfAbsent("B", 2);   // 成功
System.out.println(map); // 輸出 {A=1, B=2}
5. remove (條件刪除)

源碼

    default boolean remove(Object key, Object value) {Object curValue = get(key);if (!Objects.equals(curValue, value) ||(curValue == null && !containsKey(key))) {return false;}remove(key);return true;}

作用:僅當鍵值匹配時才刪除
示例

Map<String, String> map = new HashMap<>();
map.put("lang", "Java");
map.remove("lang", "Python"); // 失敗
map.remove("lang", "Java");   // 成功
6. replace (條件替換)

源碼

    default boolean replace(K key, V oldValue, V newValue) {Object curValue = get(key);if (!Objects.equals(curValue, oldValue) ||(curValue == null && !containsKey(key))) {return false;}put(key, newValue);return true;}

作用:僅當舊值匹配時才替換
示例

Map<String, String> map = new HashMap<>();
map.put("lang", "Java");
map.replace("lang", "C++", "Rust"); // 失敗
map.replace("lang", "Java", "Go");   // 成功
7. replace (無條件替換)

源碼

    default V replace(K key, V value) {V curValue;if (((curValue = get(key)) != null) || containsKey(key)) {curValue = put(key, value);}return curValue;}

作用:替換存在的key的值
示例

Map<String, String> map = new HashMap<>();
map.put("lang", "Java");
map.replace("lang", "Go");  // 成功
map.replace("os", "Linux"); // 無效果
8. computeIfAbsent

源碼

    default V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction) {Objects.requireNonNull(mappingFunction);V v;if ((v = get(key)) == null) {V newValue;if ((newValue = mappingFunction.apply(key)) != null) {put(key, newValue);return newValue;}}return v;}

作用:key不存在時通過函數生成值
示例

Map<String, List<String>> map = new HashMap<>();
map.computeIfAbsent("fruits", k -> new ArrayList<>()).add("Apple");
System.out.println(map); // 輸出 {fruits=[Apple]}

springboot源碼中的

	public static SpringFactoriesLoader forResourceLocation(String resourceLocation, @Nullable ClassLoader classLoader) {Assert.hasText(resourceLocation, "'resourceLocation' must not be empty");ClassLoader resourceClassLoader = (classLoader != null ? classLoader :SpringFactoriesLoader.class.getClassLoader());Map<String, SpringFactoriesLoader> loaders = cache.computeIfAbsent(resourceClassLoader, key -> new ConcurrentReferenceHashMap<>());return loaders.computeIfAbsent(resourceLocation, key ->new SpringFactoriesLoader(classLoader, loadFactoriesResource(resourceClassLoader, resourceLocation)));}

說明
cache類型為ConcurrentReferenceHashMap

static final Map<ClassLoader, Map<String, SpringFactoriesLoader>> cache = new ConcurrentReferenceHashMap<>();

使用computeIfAbsent,查看有沒有以resourceClassLoader為key的值,如果沒有,則new一個ConcurrentReferenceHashMaploaders

Map<String, SpringFactoriesLoader> loaders = cache.computeIfAbsent(resourceClassLoader, key -> new ConcurrentReferenceHashMap<>());

接著看loaders中有沒有以resourceLocationkey的值,沒有的話,則new一個SpringFactoriesLoader并返回

9. computeIfPresent

源碼

    default V computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction) {Objects.requireNonNull(remappingFunction);V oldValue;if ((oldValue = get(key)) != null) {V newValue = remappingFunction.apply(key, oldValue);if (newValue != null) {put(key, newValue);return newValue;} else {remove(key);return null;}} else {return null;}}

作用:key存在時通過函數計算新值
示例

Map<String, Integer> map = new HashMap<>();
map.put("count", 5);
map.computeIfPresent("count", (k, v) -> v * 2); // 變為10
map.computeIfPresent("total", (k, v) -> v + 1); // 無變化
10. compute

源碼

    default V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction) {Objects.requireNonNull(remappingFunction);V oldValue = get(key);V newValue = remappingFunction.apply(key, oldValue);if (newValue == null) {// delete mappingif (oldValue != null || containsKey(key)) {// something to removeremove(key);return null;} else {// nothing to do. Leave things as they were.return null;}} else {// add or replace old mappingput(key, newValue);return newValue;}}

作用:動態計算鍵的新值(處理存在/不存在情況)
示例

Map<String, Integer> map = new HashMap<>();
map.put("a", 2);
map.compute("a", (k, v) -> v == null ? 0 : v + 1); // a=3
map.compute("b", (k, v) -> v == null ? 0 : v + 1); // b=0
11. merge

源碼

    default V merge(K key, V value,BiFunction<? super V, ? super V, ? extends V> remappingFunction) {Objects.requireNonNull(remappingFunction);Objects.requireNonNull(value);V oldValue = get(key);V newValue = (oldValue == null) ? value :remappingFunction.apply(oldValue, value);if (newValue == null) {remove(key);} else {put(key, newValue);}return newValue;}

作用:合并鍵值(處理null值)
示例

Map<String, String> map = new HashMap<>();
map.put("lang", "Java");
map.merge("lang", "Script", (oldV, newV) -> oldV + newV); // JavaScript
map.merge("new", "Key", (oldV, newV) -> oldV + newV);     // Key
12. of (創建不可變Map,這是一個重載的方法)

源碼

  static <K, V> Map<K, V> of() {return (Map<K,V>) ImmutableCollections.EMPTY_MAP;}

作用:創建0-10個元素的不可變Map
示例

Map<String, Integer> empty = Map.of();
Map<String, Integer> single = Map.of("a", 1);
Map<String, Integer> multiple = Map.of("a", 1, "b", 2);
// 嘗試修改會拋 UnsupportedOperationException
13. ofEntries

源碼

   static <K, V> Map<K, V> ofEntries(Entry<? extends K, ? extends V>... entries) {if (entries.length == 0) { // implicit null check of entries array@SuppressWarnings("unchecked")var map = (Map<K,V>) ImmutableCollections.EMPTY_MAP;return map;} else if (entries.length == 1) {// implicit null check of the array slotreturn new ImmutableCollections.Map1<>(entries[0].getKey(),entries[0].getValue());} else {Object[] kva = new Object[entries.length << 1];int a = 0;for (Entry<? extends K, ? extends V> entry : entries) {// implicit null checks of each array slotkva[a++] = entry.getKey();kva[a++] = entry.getValue();}return new ImmutableCollections.MapN<>(kva);}}

作用:通過Entry對象創建不可變Map
示例

Map.Entry<String, Integer> e1 = Map.entry("a", 1);
Map.Entry<String, Integer> e2 = Map.entry("b", 2);
Map<String, Integer> map = Map.ofEntries(e1, e2);
14. entry

源碼

    static <K, V> Entry<K, V> entry(K k, V v) {// KeyValueHolder checks for nullsreturn new KeyValueHolder<>(k, v);}

作用:創建鍵值對Entry對象
示例

Map.Entry<String, Integer> entry = Map.entry("key", 100);
System.out.println(entry.getKey() + ":" + entry.getValue());
15. copyOf

源碼

    static <K, V> Map<K, V> copyOf(Map<? extends K, ? extends V> map) {if (map instanceof ImmutableCollections.AbstractImmutableMap) {return (Map<K,V>)map;} else {return (Map<K,V>)Map.ofEntries(map.entrySet().toArray(new Entry[0]));}}

作用:創建Map的不可變副本
示例

Map<String, Integer> original = new HashMap<>();
original.put("a", 1);
Map<String, Integer> copy = Map.copyOf(original);
// 修改original不影響copy

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/83502.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/83502.shtml
英文地址,請注明出處:http://en.pswp.cn/web/83502.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

山東大學 2025 web數據管理期末復習總結

SDU-2025年-Web數據管理期末總結 考試題型 填空 &#xff1a;都來自于PPT中名詞解釋簡答題&#xff1a;需要背一些公式。 根據L老師上課提及的重點一共總結了87問題。 文章目錄 SDU-2025年-Web數據管理期末總結考試題型第1講 緒論此章不考 第2講 網絡爬蟲技術2.1 爬蟲是什么…

Spring框架的設計模式

Spring 框架深度集成了多種經典設計模式&#xff0c;這些模式支撐了其核心功能&#xff08;如IoC、AOP&#xff09;的實現&#xff0c;以下是關鍵模式及其應用場景的梳理&#xff1a; 1、工廠模式 工廠模式&#xff08;Factory Pattern&#xff09;是 Java 中最常用的設計模式…

git報錯fatal: 遠端意外掛斷了

git報錯fatal: 遠端意外掛斷了 報錯詳細內容 mr.mbogon tinymce % git add . mr.mbogon tinymce % git commit -m init [master c6cfc2a] init1 file changed, 2 insertions(), 1 deletion(-) mr.mengbogon tinymce % git push 枚舉對象中: 241, 完成…

Windows 下安裝 NVM

NVM 下載 NVM 在工作中&#xff0c;你可能遇到過某個項目需要高版本的 node 才能運行&#xff0c;而有的項目可能只支持低版本的 node&#xff0c;此時就可以借助于一些 Node 版本管理工具&#xff0c;比如 nvm&#xff08;Node Version Manager&#xff09;&#xff0c;幫助…

AI知識補全(十七):通用人工智能AGI是什么?

名人說:博觀而約取,厚積而薄發。——蘇軾《稼說送張琥》 創作者:Code_流蘇(CSDN)(一個喜歡古詩詞和編程的Coder??) 上一篇:AI知識補全(十六):A2A - 谷歌開源的agent通信協議是什么? 目錄 一、什么是AGI?概念解析1. 什么是AGI2. AGI與現有AI的本質區別二 、AGI的核…

Spring Cloud Gateway 介紹

什么是Spring Cloud Gateway&#xff1f; Spring Cloud Gateway 是 Spring Cloud 社區官方推出的一個基于 Spring Framework 5、Project Reactor 和 Spring Boot 2.x 的下一代 API 網關&#xff08;API Gateway&#xff09;解決方案。它旨在為微服務架構提供統一、簡潔、高效的…

slam--高斯分布

教程 博主解釋 高斯分布 高斯分布&#xff08;Gaussian Distribution&#xff09;&#xff0c;又稱正態分布&#xff08;Normal Distribution&#xff09;&#xff0c;是描述連續型隨機變量分布規律的一種概率分布。 (1) 一維高斯分布 μ&#xff1a;均值/數學期望&#xff0…

機器視覺標定講解

B站 &#xff1a;道傳科技上位機 觀看教程 一、什么是相機標定 相機標定&#xff08;Camera Calibration&#xff09;是指通過實驗或算法手段確定相機的內部參數&#xff08;如焦距、主點坐標、畸變系數&#xff09;和外部參數&#xff08;如旋轉矩陣、平移向量&#xff0…

文件的秒傳、分片上傳以及斷點續傳 || Redis緩存減輕數據庫讀寫壓力

實現文件的秒傳、分片上傳以及斷點續傳的功能。使用 Redis 緩存上傳的文件分片信息減輕數據庫讀寫壓力&#xff0c;同時防止有人惡意攻擊服務器導致服務器磁盤爆滿無法提供服務。 &#x1f50d; 詳解&#xff1a; 1. 實現文件的秒傳、分片上傳以及斷點續傳功能 秒傳&#xff0…

安全大模型智驅網絡和數據安全效能躍遷

從2023年ChatGPT開始&#xff0c;網絡安全行業就一直嘗試和AI大模型來結合&#xff0c;解決網絡安全的痛點&#xff0c;例如告警多&#xff0c;專家少&#xff0c;新的APT攻擊層出不窮&#xff0c;已有的基于規則的防護手段失靈&#xff0c;如何使用大模型的泛化能力來提升對未…

Android S - 恢復部分應用安裝

使用展銳提供的代碼編譯出來的固件&#xff0c;不包含DeskClock等應用。 之前也遇到過這個情況&#xff0c;只是時間太久忘記了&#xff0c;在這里再次記錄&#xff01; frameworks/native/data/etc/android.app.remove.xml<?xml version"1.0" encoding"ut…

android 之 CALL

一、組件職責與定位 組件所在進程核心職責關鍵特性CallsManagerTelecom系統進程通話狀態機核心&#xff1a;管理所有Call對象的生命周期&#xff08;創建、狀態更新、銷毀&#xff09;。監聽Call狀態變化并通知所有觀察者&#xff08;如InCallController&#xff09;。通過mLi…

Swift 6 學習筆記(二)The Basics

這篇筆記也是同步 Swift 6 官方教程中的第二篇 《The Basics》&#xff0c;這篇博客中的大部分內容在第一篇中已經涉及&#xff0c;這篇可以被認為是基礎類型的的補充篇&#xff0c;多了很多說明信息。 官方教學文檔 《The Basics》&#xff1a; Swift 提供了許多基本數據類型…

【PHP】BC Math 函數參考表

BC Math 函數參考表: 函數名描述語法bcadd兩個任意精度數字的加法bcadd($num1, $num2, [scale])bcsub兩個任意精度數字的減法bcsub($num1, $num2, [scale])bcmul兩個任意精度數字乘法bcmul($num1, $num2, [scale])bcdiv兩個任意精度數字除法bcdiv($num1, $num2, [scale])bcmod…

C# TAP異步編程(Task/async/await)總結

C#中有個很好用的東西&#xff0c;TAP異步編程&#xff08;Task-based Asynchronous Pattern&#xff09;&#xff0c;是目前C#推薦的異步編程模型。它基于 System.Threading.Tasks.Task 和 async/await 關鍵字&#xff0c;旨在簡化異步代碼的編寫、調試和維護。TAP 是現代 .NE…

達夢數據庫(DM)用戶名大小寫處理規則

達夢數據庫(DM)用戶名大小寫處理規則 達夢數據庫對用戶名的處理與PostgreSQL和Oracle有所不同&#xff0c;以下是相關說明&#xff1a; 一、基本規則 默認情況下&#xff1a;達夢數據庫區分用戶名大小寫 創建的用戶名會保留原始大小寫格式連接時必須使用相同的大小寫形式 …

黑馬點評面試話術

文章目錄 1.項目介紹2. 分布式登錄功能2.1 講講登錄的整個流程2.2 集群模式session下存儲用戶信息會有啥問題&#xff1f;2.3 為什么采用redis存儲用戶信息和驗證碼2.4 redis的存儲格式怎么樣的&#xff1f;2.5 為什么采用Hash結構存儲用戶信息2.6 為什么采用雙攔截器&#xff…

MTK APEX測光系統中各變量具體的計算方式探究

目錄 一、APEX測光系統介紹 二、MTK測光系統實例介紹 三、關于測光系統的一些疑問 一、APEX測光系統介紹 詳細內容可以參考; AE(自動曝光)系統簡介

K8S的基本概念

Kubernetes是一個開源的容器編排部署管理平臺,用于管理云平臺中多個主機上的容器化應用。Kubernetes的目標是讓部署容器化的應用簡單并且高效,Kubernetes提供了應用部署、規劃、更新、維護的一種機制。 對應用開發者而言,可以把Kubernetes看成一個集群操作系統。Kubernetes…

NLP學習路線圖(三十四): 命名實體識別(NER)

一、命名實體識別(NER)是什么? 命名實體識別(Named Entity Recognition, NER)是自然語言處理中的一項關鍵序列標注任務。其核心目標是從非結構化的文本中自動識別出特定類別的名詞性短語,并將其歸類到預定義的類別中。 核心目標:找到文本中提到的命名實體,并分類。 典…