【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
    }
}

下一篇文章:

相关推荐
无敌最俊朗@7 分钟前
SQLite 约束 (Constraints) 面试核心知识点
java·开发语言·jvm
QX_hao22 分钟前
【Go】--接口(interface)
开发语言·后端·golang
憨憨崽&33 分钟前
C语言、Java、Python 的选择与未来发展以及学习路线
java·c语言·python
西西学代码43 分钟前
Flutter---个人信息(1)---实现简单的UI
开发语言·javascript·flutter
superman超哥1 小时前
仓颉语言中正则表达式引擎的深度剖析与实践
开发语言·后端·仓颉
在坚持一下我可没意见1 小时前
Java 网络编程:TCP 与 UDP 的「通信江湖」(基于UDP回显服务器)
java·服务器·开发语言·tcp/ip·udp·java-ee
少爷晚安。1 小时前
Java零基础学习完整笔记,基于Intellij IDEA开发工具,笔记持续更新中
java·笔记·学习
悟能不能悟1 小时前
在service方法中已经catch异常,Transactional失效怎么办
java·数据库·sql
西红柿维生素1 小时前
23种设计模式-框架中的使用
java·开发语言·设计模式
LNN20221 小时前
Qt creator +Valgrind检测内存泄漏(linux)
linux·开发语言·qt