The new merge method of map in jdk8

Whether to use the code comparison of the merge method

Do not use 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);
    }
}

Use merge

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

merge source code

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;
}

This method receives three parameters, a key value, a value, and a remappingFunction. If the given key does not exist, it becomes put(key, value). However, if the key already has some values, we can choose the merge method for remappingFunction, and then assign the merged newValue to the original key.

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/108953018