jdk8中map新增的merge方法

是否使用merge方法的代码比较

不使用merge

Map<Byte, Integer> counts = new HashMap<>();
for (byte b : bytes) {
    
    
    Integer count = counts.get(b);
    if (count == null) {
    
    
        // Map仍然没有该字符数据
        counts.put(b, 1);
    } else {
    
    
        counts.put(b, count + 1);
    }
}

使用merge

Map<Byte, Integer> counts = new HashMap<>();
for (byte b : bytes) {
    
    
    // Map仍然没有该字符数据
    counts.merge(b, 1, Integer::sum);
}

merge源码

defaultV merge(K key, V value,
        BiFunction<? super V, ? super V, ? extends V> remappingFunction) {
    
    
    Objects.requireNonNull(remappingFunction);
    Objects.requireNonNull(value);
    V oldValue = get(key);
    //1.给的key值的value为空,赋值newValue.  如果给的key值的value不为空,使用传过来的函数处理 oldValue和 newValue 
    V newValue = (oldValue == null) ? value :
               remappingFunction.apply(oldValue, value);
    //若果处理后的newValue为空,移除当前值
    if(newValue == null) {
    
    
        remove(key);
    } else {
    
    
    //若果处理后的newValue为空, put操作          
        put(key, newValue);
    }
    return newValue;
}

该方法接收三个参数,一个 key 值,一个 value,一个 remappingFunction ,如果给定的key不存在,它就变成了 put(key, value) 。但是,如果 key 已经存在一些值,我们 remappingFunction 可以选择合并的方式,然后将合并得到的 newValue 赋值给原先的 key。

猜你喜欢

转载自blog.csdn.net/KaiSarH/article/details/108953018