在开发过程中,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
总结一下,就是原来的参数是空的,就直接新参数覆盖,原来的参数不为空,就按照设定好的规则处理后覆盖原有的参数