java 8中map中compute,computeIfAbsent,computeIfPresent方法介绍

compute(计算)

default V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)app

指定的key值在map中的value值进行操做, 若是key存在,则可操做value值; 若是key不存在,操做完成后key,value都保存到map中函数

Map<String,Integer> map= Maps.newHashMap();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        
        Integer integer = map.compute("3", (k,v) -> v+1 );
        System.out.println(map);
        Integer integer1 = map.compute("4", (k,v) -> v=9);
        System.out.println(map);
        
    输出:   
    {1=1, 2=2, 3=4}
    {1=1, 2=2, 3=4, 4=9}

computeIfAbsent(不存在时计算)

V computeIfAbsent(K key,Function<? super K, ? extends V> mappingFunction)code

第一个是所选map的key,第二个是须要作的操做。这个方法当key值不存在时才起做用。当key存在返回当前value值,不存在执行函数并保存到map中.rem

Map<String, Integer> map = Maps.newHashMap();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        //key值存在,则不作操做
        map.computeIfAbsent("1", key -> 90);
        System.out.println(map);
        //key 值不存在,则作操做
        map.computeIfAbsent("4", key -> 90);
        System.out.println(map);
        
    输出:
    {1=1, 2=2, 3=3}
    {1=1, 2=2, 3=3, 4=90}

computeIfPresent(存在时计算)

default V computeIfPresent(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)io

对指定的在map中已经存在的key的value进行操做。只对已经存在key的进行操做,其余不操做map

Map<String, Integer> map = Maps.newHashMap();
        map.put("1", 1);
        map.put("2", 2);
        map.put("3", 3);
        //key值存在则计算
        map.computeIfPresent("3", (key, value) -> value = 10);
        System.out.println(map);
        //key值不存在,则不作操做
        map.computeIfPresent("4", (key, value) -> 90);
        System.out.println(map);
    输出:
    {1=1, 2=2, 3=10}
    {1=1, 2=2, 3=10}
相关文章
相关标签/搜索