在开发过程中,IDEA提示我可以用Map.merge()方法优化代码,我就去看了下代码

首先是优化前后的代码对比
Map<Long,String> heightMap = new HashMap<>();
String heights = heightMap.get(subId);
if (heights == null) {
heightMap.put(subId,height);
} else {
heightMap.put(subId,heights + "," + height);
}
Map<Long,String> heightMap = new HashMap<>();
heightMap.merge(subId, height, (a, b) -> a + "," + b);
明显可以看到代码整洁了不少,不过由于这个方法之前没用过,我还是进去看了看源码

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;
}
首先调用了Objects类里面的requireNonNull()方法,这个方法的作用是判断参数是否为空,如果参数为空就会抛出异常
public static <T> T requireNonNull(T obj) {
if (obj == null)
throw new NullPointerException();
return obj;
}
说明Map.merge()方法的参数不能为空
然后先用get()方法取出map中对应key的oldValue
如果oldValue为空的话,直接把新输入的参数value赋值给newValue,否则的话按照传入的设定好的规则组装参数,比如我的代码里面,就是(a, b) -> a + "," + b
然后如果newValue为空的话,就从map中直接把这个key给remove掉,如果不为空,就把newValue赋值给key
总结一下,就是原来的参数是空的,就直接新参数覆盖,原来的参数不为空,就按照设定好的规则处理后覆盖原有的参数

本文介绍了如何使用Java中的Map.merge()方法简化代码。通过比较优化前后的代码示例,展示了Map.merge()如何在键值对存在时根据指定规则合并值。在原有值为空时直接替换,非空时应用提供的BiFunction进行合并。该方法提高了代码的简洁性和可读性。
434

被折叠的 条评论
为什么被折叠?



