java Map接口的computeIfPresent和putIfAbsent方法介绍
用于在映射中存在指定键时,计算并更新该键的值。如果计算结果为null,则键会从映射中删除。:用于在映射中不存在指定键时插入新键值对。如果键已经存在,则不会进行插入操作,并返回现有值。这两个方法都简化了对映射的操作,使得更新和插入操作更加简洁且减少了条件检查的需要。
·
Map接口中的computeIfPresent和putIfAbsent方法是Java 8引入的两个有用的方法,用于操作映射中的值。它们使得对映射的更新操作更加简洁和灵活。以下是这两个方法的详细介绍:
computeIfPresent 方法
方法签名
V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
参数
key:要检查的映射中的键。remappingFunction:一个BiFunction,它接受两个参数:键和当前值,并返回新的值。如果remappingFunction返回null,则键将从映射中删除。
返回值
- 返回映射中指定键的新值。如果
remappingFunction返回null,则键将从映射中删除,方法返回null。如果键不存在于映射中,方法将返回null。
功能
- 如果映射中存在指定的键,则应用
remappingFunction来计算该键的新值,并将其替换原有值。 - 如果
remappingFunction返回null,则从映射中移除该键。
示例
import java.util.*;
public class ComputeIfPresentExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 2);
map.put("banana", 3);
// 仅在存在键 "apple" 时更新其值
map.computeIfPresent("apple", (key, value) -> value + 1);
// 结果: {apple=3, banana=3}
System.out.println(map);
// 键 "grape" 不存在,所以不做任何操作
map.computeIfPresent("grape", (key, value) -> value + 1);
// 结果: {apple=3, banana=3}
System.out.println(map);
// 将 "apple" 的值设置为 null,这将移除 "apple"
map.computeIfPresent("apple", (key, value) -> null);
// 结果: {banana=3}
System.out.println(map);
}
}
putIfAbsent 方法
方法签名
V putIfAbsent(K key, V value)
参数
key:要插入或检查的键。value:如果键不存在于映射中,则插入的值。
返回值
- 返回映射中指定键的旧值,如果该键之前已存在。如果键不存在,则返回
null。
功能
- 如果映射中已经包含指定的键,则不会更新映射中的值,方法返回旧值。
- 如果映射中不包含该键,则将指定的值插入映射中,并返回
null。
示例
import java.util.*;
public class PutIfAbsentExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 2);
map.put("banana", 3);
// 键 "apple" 已存在,不会插入新值,返回旧值 2
Integer oldValue = map.putIfAbsent("apple", 10);
// 结果: 2
System.out.println(oldValue);
// 键 "grape" 不存在,将其插入值 5,并返回 null
oldValue = map.putIfAbsent("grape", 5);
// 结果: null
System.out.println(oldValue);
// 结果: {apple=2, banana=3, grape=5}
System.out.println(map);
}
}
总结
computeIfPresent:用于在映射中存在指定键时,计算并更新该键的值。如果计算结果为null,则键会从映射中删除。putIfAbsent:用于在映射中不存在指定键时插入新键值对。如果键已经存在,则不会进行插入操作,并返回现有值。
这两个方法都简化了对映射的操作,使得更新和插入操作更加简洁且减少了条件检查的需要。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)