程序员

对Map中的所有值进行自增/自减的一种优雅方式(JDK8)

2018-11-14  本文已影响46人  alonwang

2019-01-06 一种更优雅的方式 replaceAll()

需求: 对map中的所有值统一增减

基础版本

下面这个方式是可行的,但是看着不太优雅

    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        map.forEach((key, value)->map.put(key,map.get(key)-1));
    }

误用版本--merge 有副作用

经过一番研究之后发现了一种简单的方式,但是有个限制 merge之后不能发生结构性修改(也就是map中元素数量不能发生变化),在当前场景下只要保证merge后不为空值即可

public class MapIncr {
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        map.forEach((key, value) -> map.merge(key, -1, Integer::sum));
    }
}

关键就是map.merge(),源码如下

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

可以看到如果新值为空就会被移除掉

最佳版本--replaceAll

replaceAll会对map中的所有元素使用传递进来的BiFunction进行更新.

public class MapIncr {
    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        map.replaceAll((k,v)->v+1);
    }
}

总结

上一篇 下一篇

猜你喜欢

热点阅读