java 8 中Map的computeIfAbsent,computeIfPresent,compute,merge 函数的使用

java 8 中Map的computeIfAbsent,computeIfPresent,compute,merge 函数的使用
package com.test.com;

import java.util.HashMap;
import java.util.Map;

/**
 * java 8 中Map的computeIfAbsent,computeIfPresent,compute,merge 函数的使用
 */
public class MapTest {
    public static void main(String[] args) {
        //computeIfAbsent() -- 不可以改变map中key对应的value值,map中不存在的可以加入
        Map<String, Integer> mapCIAbsent = new HashMap<>();
        //map中不存在key-value键值对,调用会加入到map
        mapCIAbsent.computeIfAbsent("a", k -> 12);
        System.out.println("mapCIAbsent--"+mapCIAbsent);
        //map中对应key-value已存在,调用不会改变key对应的value值
        mapCIAbsent.put("c", 13);
        mapCIAbsent.computeIfAbsent("c", k -> 14);
        System.out.println("mapCIAbsent--"+mapCIAbsent);

        //computeIfPresent() -- 可以改变map中key对应的value值,map中不存在的不会加入
        Map<String, Integer> mapCIPresent = new HashMap<>();
        mapCIPresent.put("a", 12);
        //map中对应key-value已存在,则使用 lambda 表达式生成新值并存储到 Map 中
        mapCIPresent.computeIfPresent("a", (k, v) -> v - 1);
        System.out.println("mapCIPresent--"+mapCIPresent);
        //map中对应key-value不存在,则不执行任何操作,不会加入到map
        mapCIPresent.computeIfPresent("b", (k, v) -> 13);
        System.out.println("mapCIPresent--"+mapCIPresent); // 输出 false

        //compute() -- 可以改变map中key对应的value值,map中不存在的可以加入
        Map<String, Integer> mapCompute = new HashMap<>();
        mapCompute.put("a", 12);
        //map中对应key-value已存在,则使用 lambda 表达式生成新值并存储到 Map 中
        mapCompute.compute("a", (k, v) -> v - 1);
        System.out.println("mapCompute--"+mapCompute);
        //map中对应key-value不存在,则使用 lambda 表达式生成新值并存储到 Map 中
        mapCompute.compute("b", (k, v) -> 13);
        System.out.println("mapCompute--"+mapCompute);

        //merge() -- 原始值和要合并的新值,并返回合并后的值
        Map<String, Integer> mapMerge = new HashMap<>();
        mapMerge.put("a", 12);
        // 合并键 "a" 的值,使用 lambda 表达式将原始值加上新值
        mapMerge.merge("a", 8, (oldValue, newValue) -> oldValue + newValue);
        System.out.println("mapMerge--"+mapMerge);
        // 合并键 "b" 的值,由于键不存在于 map 中,直接存储新值
        mapMerge.merge("b", 13, (oldValue, newValue) -> oldValue + newValue);
        System.out.println("mapMerge--"+mapMerge);
    }
}

测试结果

mapCIAbsent--{a=12}
mapCIAbsent--{a=12, c=13}
mapCIPresent--{a=11}
mapCIPresent--{a=11}
mapCompute--{a=11}
mapCompute--{a=11, b=13}
mapMerge--{a=20}
mapMerge--{a=20, b=13}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值