Map中的put、putIfAbsent、compute、computeIfAbsent、computeIfPresent使用方法

目录

1.概述

2.内容    

 2.1 put:【添加】

 2.2 putIfAbsent:【不存在则添加】

 2.3 compute:【计算】

 2.4 computeIfAbsent:【不存在则计算】

 2.5 computeIfPresent:【存在则计算】


1.概述


        Map是做软件开发中使用频率最高的数据结构之一。它的最大特点是能够快速地进行查找和更改数据,经常被用做缓存以及数据重复检查场景中。很多人在给Map赋值过程中只知道最基础的put方法,下面我将给大家详细介绍下其他赋值方法的区别。

2.内容

 2.1 put:【添加】

key不存在,直接添加,put方法返回null;

key存在,新值覆盖旧值,put方法返回旧值。

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    System.out.println("1->"+map.put(1, "a"));
    System.out.println("2->"+map.put(2, "b"));
    System.out.println("3->"+map.put(2, "c"));
    System.out.println("4->"+map);
    //控制台输出:
//    1->null
//    2->null
//    3->b
//    4->{1=a, 2=c}
}

 2.2 putIfAbsent:【不存在则添加】

key不存在,直接添加,putIfAbsent方法返回null;

key存在,不进行操作,putIfAbsent方法返回旧值。

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    System.out.println("1->"+map.putIfAbsent(1, "a"));
    System.out.println("2->"+map.putIfAbsent(2, 
<think> 我们讨论HashMap中的computeIfAbsent方法。 1. 方法定义: V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) 2. 作用: 如果指定的key尚未与值关联(或关联为null),则尝试使用给定的mappingFunction计算其值,并将其放入Map(除非为null)。 如果mappingFunction返回null,则不进行任何记录(即不会将null值放入Map),并返回null。 3. 使用场景: 常用于实现“多值Map”(即一个key对应一个集合)时,避免重复创建集合对象。 4. 示例代码: 例如,我们要将多个学生按照班级分组,可以使用computeIfAbsent来简化代码。 下面是一个使用computeIfAbsent的示例: </think> ### `HashMap.computeIfAbsent()` 方法详解 #### 📌 方法作用和语法 ```java public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) ``` - **作用**:当指定键 `key` 不存在(或映射为 `null`)时,通过 `mappingFunction` 计算值并存入映射 - **返回值**: - 键已存在 → 返回当前值 - 键不存在 → 返回计算后的新值 - **线程安全**:非线程安全(多线程环境下需用 `ConcurrentHashMap`) #### 🔧 典型使用场景 1. **初始化默认值** ```java Map<String, List<String>> departmentMap = new HashMap<>(); // 传统方式 if (!departmentMap.containsKey("IT")) { departmentMap.put("IT", new ArrayList<>()); } departmentMap.get("IT").add("Alice"); // computeIfAbsent方式 departmentMap.computeIfAbsent("IT", k -> new ArrayList<>()).add("Bob"); ``` 2. **缓存计算结果** ```java Map<Integer, BigInteger> factorialCache = new HashMap<>(); BigInteger result = factorialCache.computeIfAbsent(10, n -> factorial(n) // 复杂计算函数 ); ``` 3. **构建嵌套 Map** ```java Map<String, Map<String, Integer>> nestedMap = new HashMap<>(); nestedMap.computeIfAbsent("Asia", k -> new HashMap<>()) .put("China", 1_400_000_000); ``` #### ⚠️ 关键注意事项 1. **空值处理**: - 若 `mappingFunction` 返回 `null`,不会存入 Map - 键存在但值为 `null` 时,会触发函数计算 ```java map.put("A", null); map.computeIfAbsent("A", k -> "new"); // 返回"new",覆盖null ``` 2. **并发修改**: - 禁止在函数内修改当前 Map(抛 `ConcurrentModificationException`) ```java // 错误示例! map.computeIfAbsent("A", k -> { map.put("B", "value"); // 抛出ConcurrentModificationException return "new"; }); ``` 3. **性能影响**: - 函数应轻量(频繁调用影响性能) - 替代方案比较: ```java // 方案1:containsKey + put (可能2次哈希计算) // 方案2:get + put (需处理null) // 方案3:computeIfAbsent (1次哈希计算+条件判断) ``` #### 💡 与类似方法对比 | 方法 | 特点 | |---------------------|----------------------------------------------------------------------| | `putIfAbsent()` | 仅存在时返回原值,不触发计算;直接放入指定值 | | `compute()` | 无论是否存在都计算新值 | | `merge()` | 提供合并函数处理新旧值冲突 | | `getOrDefault()` | 不修改Map,仅返回值或默认值 | #### 🚫 常见错误案例 ```java // 错误1:递归调用导致StackOverflow Map<String, String> map = new HashMap<>(); map.computeIfAbsent("A", k -> map.computeIfAbsent("A", k2 -> "value")); // 错误2:非原子操作导致线程不安全 ConcurrentHashMap<String, Integer> safeMap = new ConcurrentHashMap<>(); safeMap.computeIfAbsent("key", k -> expensiveOperation()); // 安全版本 ``` #### ✅ 最佳实践建议 1. 优先用于**延迟初始化**场景 2. 多线程用 `ConcurrentHashMap.computeIfAbsent()` 3. 复杂计算前检查是否必要: ```java if (map.get(key) == null) { // 前置条件检查... map.computeIfAbsent(key, this::heavyCalculation); } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值