jdk1.8中map中compute,computeIfAbsent,computeIfPresent方法介紹

 

1.compute

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

compute的方法,指定的key在map中的值進行操作 不管存不存在,操作完成後保存到map中

        HashMap<String,Integer> map = new HashMap<>();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        Integer integer = map.compute("3", (k,v) -> v+1 );
        //key不管存在不在都會執行後面的函數,並保存到map中
        Integer integer1 = map.compute("4", (k,v) -> {
            if (v==null)return 0;
            return v+1;
        } );
        System.out.println(integer);
        System.out.println(integer1);
        System.out.println(map.toString());

打印結果
4
0
{1=1, 2=2, 3=4, 4=0}

2.computeIfAbsent

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

computeIfAbsent的方法有兩個參數 第一個是所選map的key,第二個是需要做的操作。這個方法當key值不存在時才起作用。

當key存在返回當前value值,不存在執行函數並保存到map中

    HashMap<String,Integer> map = new HashMap<>();
    map.put("1",1);
    map.put("2",2);
    map.put("3",3);
    Integer integer = map.computeIfAbsent("3", key -> new Integer(4));//key存在返回value
    Integer integer1 = map.computeIfAbsent("4", key -> new Integer(4));//key不存在執行函數存入
    System.out.println(integer);
    System.out.println(integer1);
    System.out.println(map.toString());


打印結果
3
4
{1=1, 2=2, 3=3, 4=4}

3.computeIfPresent

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

computeIfPresent 的方法,對 指定的 在map中已經存在的key的value進行操作。只對已經存在key的進行操作,其他不操作

        HashMap<String,Integer> map = new HashMap<>();
        map.put("1",1);
        map.put("2",2);
        map.put("3",3);
        //只對map中存在的key對應的value進行操作
        Integer integer = map.computeIfPresent("3", (k,v) -> v+1 );
        Integer integer1 = map.computeIfPresent("4", (k,v) -> {
            if (v==null)return 0;
            return v+1;
        } );
        System.out.println(integer);
        System.out.println(integer1);
        System.out.println(map.toString());


打印結果
4
null
{1=1, 2=2, 3=4}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章