答案:Map.merge()用于合并键值,若键不存在或值为null则插入新值,若键存在则按BiFunction函数更新值。

Java 的 Map.merge() 方法用于将一个值合并到指定的键中。如果键不存在,或者对应的值为 null,就直接插入新值;如果键已存在,则根据传入的函数来决定如何更新值。
方法签名
V merge(K key, V value, BiFunction super V,? super V,? extends V> remappingFunction)参数说明:
- key:要操作的键
- value:要合并的值(默认值或新增值)
- remappingFunction:当键已有原值时,用来合并旧值和新值的函数
如何用 merge 更新值
当键已存在时,merge 会调用 remappingFunction 来计算新的值。这个函数接收两个参数:
第一个是当前已存在的值(oldValue),
第二个是你传入的 value 参数(newValue),
然后返回合并后的结果。
常见使用场景包括计数、拼接字符串、累加数值等。
示例:统计单词出现次数
使用 merge 实现词频统计:
MapString[] words = {"apple", "banana", "apple", "orange", "banana", "apple"};
for (String word : words) {
wordCount.merge(word, 1, (oldCount, newValue) -> oldCount + 1);
}
// 结果: {apple=3, banana=2, orange=1}
解释:
- 第一次遇到 "apple" 时,map 中没有该键,所以直接设置为 1(忽略函数)
- 再次遇到时,oldCount 是 1,newValue 是 1,函数返回 1+1=2,更新为 2
- 后续同理,不断累加
更简洁写法
由于这里只是做累加,可以简写为:
立即学习“Java免费学习笔记(深入)”;
wordCount.merge(word, 1, Integer::sum);Integer::sum 等价于 (a,b) -> a+b,代码更清晰。
其他应用场景
-
拼接字符串:
map.merge("log", "error1", (old, newVal) -> old + "," + newVal); -
合并列表:
map.merge("users", user, (list, newUser) -> { list.add(newUser); return list; }); -
避免 null 判断:
merge 能自动处理键不存在的情况,比 putIfAbsent 更灵活
基本上就这些。merge 的核心优势是线程安全(在 ConcurrentHashMap 中)且能原子性地完成“判断是否存在 + 合并”的操作,避免了显式的 if-else 和并发问题。










