Map中的put、putIfAbsent、compute、computeIfAbsent、computeIfPresent使用方法

目录

1.概述

2.内容    

 2.1 put:【添加】

 2.2 putIfAbsent:【不存在则添加】

 2.3 compute:【计算】

 2.4 computeIfAbsent:【不存在则计算】

 2.5 computeIfPresent:【存在则计算】


1.概述


        Map是做软件开发中使用频率最高的数据结构之一。它的最大特点是能够快速地进行查找和更改数据,经常被用做缓存以及数据重复检查场景中。很多人在给Map赋值过程中只知道最基础的put方法,下面我将给大家详细介绍下其他赋值方法的区别。

2.内容

 2.1 put:【添加】

key不存在,直接添加,put方法返回null;

key存在,新值覆盖旧值,put方法返回旧值。

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    System.out.println("1->"+map.put(1, "a"));
    System.out.println("2->"+map.put(2, "b"));
    System.out.println("3->"+map.put(2, "c"));
    System.out.println("4->"+map);
    //控制台输出:
//    1->null
//    2->null
//    3->b
//    4->{1=a, 2=c}
}

 2.2 putIfAbsent:【不存在则添加】

key不存在,直接添加,putIfAbsent方法返回null;

key存在,不进行操作,putIfAbsent方法返回旧值。

public static void main(String[] args) {
    Map<Integer, String> map = new HashMap<>();
    System.out.println("1->"+map.putIfAbsent(1, "a"));
    System.out.println("2->"+map.putIfAbsent(2, 
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值