【Java】Map集合中常用方法

|-------------------------------------|---------------|
| 方法名称 | 作用 |
| V put(Key k,V value) | 添加元素 |
| V remove(K key, V value) | 根据键值删除对应的值 |
| void clear() | 清除所有键值元素 |
| boolean containsKey(Object key) | 判断集合中是否包含指定的键 |
| boolean containsValue(Object value) | 判断集合中是否包含指定的值 |
| boolean isEmpty() | 判断集合是否为空 |
| size() | 返回集合中存放元素的个数 |
[Map集合的常用方法]


示例代码

java 复制代码
package com.collection.Demo09;

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

public class Test01 {
    public static void main(String[] args) {
        Map<String, String> hashMap = new HashMap<>();
        System.out.println("========put========");
        hashMap.put("mayikt001", "小明");
        hashMap.put("mayikt002", "xiaojun");
        hashMap.put("mayikt003", "xiaoli");
        hashMap.put("mayikt003", "小王"); //键是不允许重复的,这里并不会报错,而是修改K="003"的值为V="mayikt"
        System.out.println(hashMap);//{mayikt002=xiaojun, mayikt001=小明, mayikt003=小王}
        //注意:上面遍历的顺序并不是put插入的顺序------∴元素存取是散列无序的
        System.out.println("========remove========");
        hashMap.remove("mayikt001"); //返回String类型
//        hashMap.remove("mayikt002","xiaojun");//只有键值对 都 存在才可以删除,返回Boolean类型
        hashMap.remove("xiaojun"); //没有这个键 ,执行并不报错
        System.out.println(hashMap);
        System.out.println("========clean========");
//        hashMap.clear();//清空hashMap集合中所有键值对
        System.out.println(hashMap);//{}
        System.out.println("========containsKey========");
        //判断在 hashMap集合中 是否存在 键值=mayikt002, 返回true/false
        System.out.println(hashMap.containsKey("mayikt002"));//true
        System.out.println("========containsValue========");
        System.out.println(hashMap.containsValue("xiaowang"));//false
        System.out.println(hashMap.containsValue("小王"));//true
        System.out.println(hashMap.containsValue("小明"));//false
        System.out.println("========isEmpty========");
        System.out.println(hashMap.isEmpty());//false
        HashMap<String, String> hashMap1 = new HashMap<>();
        System.out.println(hashMap1.size());//0 hashMap1中元素的个数
        HashMap<String, String> hashMap2 = null;
        System.out.println(hashMap1.isEmpty());//true
//        System.out.println(hashMap2.isEmpty());//报错.NullPointerException
    }
}

下一篇文章:

相关推荐
你喜欢喝可乐吗?10 分钟前
RuoYi-Cloud 验证码处理流程
java·spring cloud·微服务·vue
三体世界37 分钟前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
Java技术小馆39 分钟前
langChain开发你的第一个 Agent
java·面试·架构
kangkang-40 分钟前
PC端基于SpringBoot架构控制无人机(二):MavLink协议
java·spring boot·后端·无人机
Dcs1 小时前
Anthropic 爆严重安全漏洞!程序员机器沦陷
java
随心点儿1 小时前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农1 小时前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
tomcsdn311 小时前
SMTPman,smtp的端口号是多少全面解析配置
服务器·开发语言·php·smtp·邮件营销·域名邮箱·邮件服务器
EnigmaCoder1 小时前
Java多线程:核心技术与实战指南
java·开发语言
攀小黑1 小时前
阿里云 使用TST Token发送模板短信
java·阿里云