JDK 8 - computeIfAbsent,computeIfPresent,compute

本文详细介绍了JDK 8中Map接口的computeIfAbsent、computeIfPresent和compute方法,重点讨论了它们在处理键值对时的行为,特别是参数k和(k, v)的使用场景。" 107684901,9804832,C++基础教程:数学运算、随机数、数组与字符串解析,"['C++', '数学库', '随机数生成', '数组操作', '字符串处理', '结构体']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

computeIfAbsent(K key,    Function<? super K, ? extends V> mappingFunction)
        如果map里面不存在key,则执行mappingFunction
computeIfPresent(K key,    BiFunction<? super K, ? super V, ? extends V> remappingFunction)
        如果map里面存在key,则执行remappingFunction
compute(K key,    BiFunction<? super K, ? super V, ? extends V> remappingFunction)
        无论map里面是不是有key,都执行remappingFunction

注意computeIfAbsent的第二个参数是k,computeIfPresent和compute第二个参数都是(k,v)

public static void main(String[] args) {
        HashMap<String, List<String>> map = new HashMap();

        // key不存在的时候,执行后面的方法
        List<String> list1 = map.computeIfAbsent("list1", k -> new ArrayList<>());
        list1.add("addList1");
        map.put("absentExist", new ArrayList<>());
        List<String> absentExist = map.computeIfAbsent("absentExist", k -> new ArrayList<>());
        absentExist.add("aaaaaa the key is exist
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值