java 集合相关 —— map集合

map集合相关操作
import java.util.HashMap;
import java.util.Map;

public class mapTest {

    /**
     * map 集合
     */

    public static void main(String[] args) {

        // 创建一个HashMap实例,存放的数据是键值对 key-value
        //key 和 value 可以自定义数据类型,也可以是Object
        Map<Integer, String> map = new HashMap<>();

        // 添加键值对
        map.put(1, "丫丫");
        map.put(2, "花花");
        map.put(3, "萌兰");
        System.out.println("map集合中的大熊猫:"+map);


        // 获取与键关联的值
        String panda = map.get(1);
        System.out.println("获取key为1对应的熊猫:"+panda); // 输出: 1

        // 检查键是否存在
        boolean isExistKeyOne = map.containsKey(1);
        System.out.println("判断map集合中是否存在对于的key:"+isExistKeyOne);

        boolean isExistKeyTwo = map.containsKey(4);
        System.out.println("判断map集合中是否存在对于的key:"+isExistKeyTwo);


        if (map.containsKey(1)) {
            System.out.println("获取键对于的值: " + map.get(1));
        }

        // 遍历Map
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            Integer key = entry.getKey();
            String value = entry.getValue();
            System.out.println(key + " -> " + value);
        }

        //修改map中的数据
        map.put(1,"萌兰");
        System.out.println("修改后map集合中的大熊猫:"+map);

        // 删除键值对
        map.remove(1);
        System.out.println("删除后map集合中的大熊猫:"+map);

        // 清空Map
        map.clear();
        System.out.println("清空后map集合中的大熊猫:"+map);
    }

}
得到的打印结果

map集合中的大熊猫:{1=丫丫, 2=花花, 3=萌兰}
获取key为1对应的熊猫:丫丫
判断map集合中是否存在对于的key:true
判断map集合中是否存在对于的key:false
获取键对于的值: 丫丫
1 -> 丫丫
2 -> 花花
3 -> 萌兰
修改后map集合中的大熊猫:{1=萌兰, 2=花花, 3=萌兰}
删除后map集合中的大熊猫:{2=花花, 3=萌兰}
清空后map集合中的大熊猫:{}

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值